我有一个图像,该图像会在悬停时更改z索引并播放一些声音:
<div class="portraitPanel">
<img src="staticImage.jpg" class="saticImg">
<img src="staticImage.gif" class="movingImg">
<audio src="audio.mp3"></audio>
</div>
那就是jQuery
$(document).ready(function() {
$(".portraitPanel").hover(function(){
$(".movingImg").css('z-index', 3000);
$('audio')[0].play();
});
$(".portraitPanel").mouseout(function(){
$(".movingImg").css('z-index', 0);
$('audio')[0].stop();
});
});
好吧,现在我可以或多或少地工作了。但是我有该div的多个实例。我如何只在每个div上应用jQuery代码。现在,如果我将鼠标悬停在一个div上,则页面上的每个音频都在播放(是的,听起来很可爱)。我尝试摆弄
this
,但无法正常工作。有什么提示吗?这是一个jsFiddle
最佳答案
使用context
仅搜索parent
内部的元素。 hover
有两个回调。一种用于hover-in
,另一种用于hover-out
。您不需要注册额外的mouseout
事件监听器。
$(function() {
$(".portraitPanel").hover(function() {
var parent = $(this);
$(".movingImg", parent).css('z-index', 3000);
$('audio', parent)[0].play();
}, function() {
var parent = $(this);
$(".movingImg", parent).css('z-index', 0);
$('audio', parent)[0].stop();
});
});
关于jquery - 悬停时更改每个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39223108/