您好,我有一个非常基本的脚本,当您在<img>
元素上上下移动时,会将子<label>
移到其<label>
父对象中。
问题是,如果您将鼠标悬停在一个标签上。所有标签下的所有图像都移动。我试图通过在函数中添加$(this).closest
来解决此问题。但是,当添加$(this).closest
代码时,它将中断。如果您从我的代码中删除(this).closest,它可以正常工作,但会影响所有代码,而不是将单个代码悬停在上面。
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'});
});
答案 0 :(得分:4)
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'})
});
});
最后,正如评论所建议的,您可以使用$(this).find('> img')
缩短$('img', this)
,并设置“ context”参数。
答案 1 :(得分:2)
由于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>
只想让您知道并保持所有选项处于打开状态。