我正在尝试创建一个画廊/轮播小部件,如果该特定图像有鼠标悬停事件,它将在每个图像上显示一个 div。 到目前为止,我有这段代码来显示 div:
$(document).ready(function(){
$(".background").mouseover(function(){
$(".info").show(1500);
});
$(".background").mouseout(function(){
$(".info").hide(1500);
});
});
和 html 方面
<div id="wrapper">
<div id="slides">
<ul>
<li>
<img class="background" src="images/1.png" width="240" height="240"/>
<div class="info">Thats the info of this image</div>
</li>
<li>
<img src="images/ogm.png" width="240" height="240"/>
<div class="info">Thats the info of this image</div>
</li>
<li><img src="images/2.jpg" width="240" height="240"/>
<div class="info">Thats the info of this image</div>
</li>
<li>
<img src="images/3.png" width="240" height="240"/>
<div class="info">Thats the info of this image</div>
</li>
<li>
<img src="images/4.png" width="240" height="240"/>
<div class="info">Thats the info of this image</div>
</li>
<li>
<img src="images/5.png" width="240" height="240"/>
<div class="info">Thats the info of this image</div>
</li>
</ul>
</div>
info 是 div,background 是图像的类
正如预期的那样,当鼠标悬停在任何图像上时,所有信息 div 都会匹配并显示。
是否可以只显示触发鼠标悬停的背景图像中包含的特定信息 div?
最佳答案
您提供给 jQuery 绑定(bind)函数的回调作为引发事件的元素的上下文 (this
) 提供。因此,您可以从 $(this)
搜索 '.info'
:
$(document).ready(function(){
$(".background").mouseover(function(){
$(this).parent().find(".info").show(1500);
});
$(".background").mouseout(function(){
$(this).parent().find(".info").hide(1500);
});
});
或者(雷纳托的建议):
$(document).ready(function(){
$(".background").mouseover(function(){
$(this).sibblings(".info").show(1500);
});
$(".background").mouseout(function(){
$(this).sibblings(".info").hide(1500);
});
});
请注意,jQuery 允许链接:
$(document).ready(function(){
$(".background").mouseover(function(){
$(this).parent().find(".info").show(1500);
}).mouseout(function(){
$(this).parent().find(".info").hide(1500);
});
});
另请注意,大多数情况下您需要 mouseenter和 mouseleave而不是 mouseover
和 mouseout
。
关于jquery 匹配触发事件的 div 的子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761519/