使用Jquery更改悬停时的其他类显示
好的,这就是我要做的。我有一个DIV框,其子元素设置为DISPLAY:NONE;。我试图使用Jquery,这样当鼠标进入父DIV框时,子元素就变得可见,然后在鼠标离开父DV时隐藏。页面上将有多个包含这些类的div。由于某种原因,它不起作用。有什么想法吗?这是我的密码: HTML:使用Jquery更改悬停时的其他类显示,jquery,css-selectors,traversal,Jquery,Css Selectors,Traversal,好的,这就是我要做的。我有一个DIV框,其子元素设置为DISPLAY:NONE;。我试图使用Jquery,这样当鼠标进入父DIV框时,子元素就变得可见,然后在鼠标离开父DV时隐藏。页面上将有多个包含这些类的div。由于某种原因,它不起作用。有什么想法吗?这是我的密码: HTML: 使用find: $(document).ready(function () { $('.parent').mouseenter(function(){ $(this).find('.handle
使用
find
:
$(document).ready(function () {
$('.parent').mouseenter(function(){
$(this).find('.handle').show();
});
$('.parent').mouseleave(function(){
$(this).find('.handle').hide();
});
})
或者更好,试试这个:
$(document).ready(function () {
$('.parent').hover(function(){
$('.handle', this).show();
},
function(){
$('.handle', this).hide();
});
);
})
我建议您使用
悬停
。这意味着您只需要运行一次查询
$('div.parent').hover(
function () {
$(this).children('span.handle').show();
},
function () {
$(this).children('span.handle').hide();
}
);
您可以在没有jQuery的情况下实现您的目标:
.parent .handle{
display:none;
}
.parent:hover .handle{
display:inline;
}
<div class="parent">
<span class="handle">My Handle</span>
<p>Child Text</p>
</div>
.parent.handle{
显示:无;
}
.parent:悬停。句柄{
显示:内联;
}
我的把手
子文本
您可能应该只使用CSS,因为它消除了对Javascript的需求
已测试的FF和Safari请尝试以下方法:
$(document).ready(function () {
$('.parent').mouseenter(function(){
$(this).next('.handle').show();
}).mouseleave(function(){
$(this).next('.handle').hide();
});
})
我建议指定元素类型。它使查询速度加快了一点。@chaospandio:OP可能希望将元素从
span
更改为其他元素。尽可能保持通用性,以避免将来出现问题。这不起作用。一旦元素被隐藏,我就无法检测到它。仅在Firefox中测试。最后,我使用jQuery进行更多操作,而不仅仅是更改显示,但这是一个很好的解决方案。谢谢您是否考虑过下面唯一的CSS解决方案?
.parent .handle{
display:none;
}
.parent:hover .handle{
display:inline;
}
<div class="parent">
<span class="handle">My Handle</span>
<p>Child Text</p>
</div>
$(document).ready(function () {
$('.parent').mouseenter(function(){
$(this).next('.handle').show();
}).mouseleave(function(){
$(this).next('.handle').hide();
});
})