$(this).最接近添加到脚本时不起作用



您好,我有一个非常基本的脚本,当您将鼠标悬停在<label>元素上和<label>元素上时,它会将子<img>移动到其父元素内。

问题是,如果将鼠标悬停在一个标签上。所有标签下的所有图像都会移动。这个我不要。我试图通过向我的函数添加$(this).closest来解决这个问题。但是当添加$(this).closest代码时,它会中断。如果你从我的代码中删除(this(.closes,它可以正常工作,但它会影响所有这些,而不是悬停在单个上面。

.HTML

<div class="checkbox-cover images-true">
<div>
<label> <img></img> </label>
<label> <img></img> </label>
<label> <img></img> </label>
<label> <img></img> </label>
</div>
</div>

jQuery

$(".checkbox-cover.images-true>div>label").hover(
function () {
$(this).closest('img').stop().animate({top: '-200px'});
}, function (){
$(this).closest('img').stop().animate({top: '0'});        
});

closest搜索向上(祖先(而不是向下(后代(的 DOM 树,你真正想要的是find

$(".checkbox-cover.images-true > div > label").hover(
function () {
$(this).find('> img').stop().animate({top: '-200px'});
}, function () {
$(this).find('> img').stop().animate({top: '0'})
});        
});

最后,正如注释所建议的,您可以使用$('img', this)缩短$(this).find('> img'),设置"上下文"参数。

由于img是这里的label子级,closest用于获取与选择器匹配的最接近的父级。试试这个:

$(".checkbox-cover.images-true>div>label").hover(
function() {
$('img', this).stop().animate({top: '-200px'});
},
function() {
$('img', this).stop().animate({top: '0'});
}
);

此外,您可以仅使用 CSS 来实现这一点,例如:

.images-true label img {
position: relative;
transition: all 1s ease 0s;
top: 0;
}
.images-true label:hover img {
top: -200px;
}
<div class="checkbox-cover images-true">
<div>
<label> <img src="http://via.placeholder.com/100x100"></img> </label>
<label> <img src="http://via.placeholder.com/100x100"></img> </label>
</div>
</div>

只是想让你知道它并保持你所有的选择开放。

最新更新