Jquery 嵌套元素悬停句柄
总之,我遇到了一个处理嵌套元素悬停处理程序的问题。似乎当鼠标进入Jquery 嵌套元素悬停句柄,jquery,Jquery,总之,我遇到了一个处理嵌套元素悬停处理程序的问题。似乎当鼠标进入childdiv时,祖先也处于hover状态,当鼠标进入child元素时,是否有任何方法触发祖先的hoverout事件 下面是我到目前为止试图做到的。请复习一下 <style> div { border:1px solid red; margin:10px; padding:10px; } </style> <script> $(function() {
child
div时,祖先也处于hover
状态,当鼠标进入child
元素时,是否有任何方法触发祖先的hoverout
事件
下面是我到目前为止试图做到的。请复习一下
<style>
div
{
border:1px solid red;
margin:10px;
padding:10px;
}
</style>
<script>
$(function() {
$('div').each(function(){
var current = this;
$(this).hover(function(event){
event.stopPropagation();// doesn't work.
console.log('Capture for hover in ' + current.tagName + '#'+ current.id +
' target is ' + event.target.id); },
function(event){
event.stopPropagation();
console.log('Capture for hover out' + current.tagName + '#'+ current.id +
' target is ' + event.target.id); });
});
});
</script>
<body id="greatgrandpa">
<div id="grandpa">
<div id="parent">
<div id="child"/>
</div>
</div>
</body>
div
{
边框:1px纯红;
利润率:10px;
填充:10px;
}
$(函数(){
$('div')。每个(函数(){
无功电流=此;
$(this).hover(函数(事件){
event.stopPropagation();//不起作用。
console.log('current.tagName+'#'+current.id中悬停的捕获+
'目标是'+event.target.id);},
功能(事件){
event.stopPropagation();
console.log('悬停输出捕获'+current.tagName+'#'+current.id+
'目标是'+event.target.id);});
});
});
改用mouseover和mouseout事件
$(function() {
$('div').on('mouseover', function(e){
e.stopPropagation();
$(this).addClass('my-bg');
}).on('mouseout', function(e){
$(this).removeClass('my-bg');
})
});
演示:
注意:不需要迭代每个div,然后为每个div添加事件处理程序,您只需调用
$('div')。hover(…)
,它将为所有div注册hover
处理程序,您需要找到targetDOM
是否为子
示例
$(this).hover(function(e){
if($(e.target).is('div#child'))
{
// your child span is being hovered over
e.stopPropagation();
}
else if($(e.target).is('div#parent'))
{
// your parent element is being hovered over
}
});
.hover()
方法为mouseenter
和mouseleave
事件绑定处理程序。您可以使用它在鼠标位于元素内期间简单地将行为应用于元素
但是,如果使用mouseover
和mouseout
事件,则当鼠标移入和移出元素及其子体时,将触发这些事件
有关示例的另一种尝试,请参阅。是否只需删除asterix并在图像上运行该函数?您正在一个循环中附加事件处理程序,该循环迭代页面上的所有元素!嗨,@adeneo,我只是更新了问题,让它更清楚。请检查一下。谢谢。我真的不明白,但是你可以将mouseenter/leave函数设置为任何你想要的,像这样??嗨,@adeneo,想象一下,如果我们不知道主体中有多少嵌套的div元素呢?也许孩子有巢穴元素。我只是演示一个简单的案例。谢谢。@Joe.wang始终欢迎您……我只是试图根据您的代码回答问题,所以我想为什么编辑代码会给出适合当前代码的解决方案。@Arun P Johny,您好,@code>hoverin hoverout
和mouseover mouseout
之间的区别?谢谢。你可以看看像这样的帖子。在我得到你的答案之前,它让我很困惑。谢谢,