求助:鼠标悬停时为多元素对应id添加/移除typewriter类异常
解决鼠标悬停时为对应文本添加/移除typewriter类的问题
你的核心问题出在HTML中重复使用了同一个ID textanimation——HTML规范里ID必须是页面唯一的,document.getElementById()只会返回第一个匹配的元素,所以只有第一个<p>元素能被选中添加/移除类,其余的都不会生效。而显示隐藏div的功能正常,是因为你用了唯一的ID(dfirstdiv、dseconddiv等)来定位元素。
解决方案
- 把所有
<p>的id="textanimation"改成class="textanimation",避免ID重复。 - 在hover事件中,通过当前
<h1>找到对应的.hover_img容器,再在容器内找到.textanimation元素,精准操作当前悬停项对应的文本元素。
修改后的完整代码
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section class="sectionhome"> <div class="row verticalalign"> <div class="col"> <div> <h1 id="firstdiv">Brand</h1> </div> <div class="hover_img" id="dfirstdiv"> <p class="textanimation subtitle">There are many variations of passages of Lorem Ipsum available</p> <img src="https://picsum.photos/200/300"> </div> <div> <h1 id="seconddiv">Servizi</h1> </div> <div class="hover_img" id="dseconddiv"> <p class="textanimation subtitle">There are many variations of passages of Lorem Ipsum available</p> <img src="https://picsum.photos/200/300"> </div> <div> <h1 id="thirddiv">B2B</h1> </div> <div class="hover_img" id="dthirddiv"> <p class="textanimation subtitle">There are many variations of passages of Lorem Ipsum available</p> <img src="https://picsum.photos/200/300"> </div> </div> </div> </section>
JavaScript代码
$(document).ready(function() { $('h1').hover(function(){ // 找到当前h1对应的hover_img容器,再选中里面的textanimation元素 const targetText = $('#d' + $(this).prop('id')).find('.textanimation'); targetText.addClass('typewriter'); $('#d' + $(this).prop('id')).show(); }, function() { const targetText = $('#d' + $(this).prop('id')).find('.textanimation'); targetText.removeClass('typewriter'); $('#d' + $(this).prop('id')).hide(); }); });
CSS代码(保持原代码即可)
.first { display:none; } .hover_img { display:none; }
内容的提问来源于stack exchange,提问作者ateve
相关产品推荐
相关产品推荐

