所有,我遇到了一个处理嵌套元素悬停处理程序的问题。似乎当鼠标进入child
div时,祖先也处于hover
状态,当鼠标进入hoverout
时,是否有任何方法触发祖先的child
事件元件?
以下是我到目前为止要做的事情。请查看它。
<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>
答案 0 :(得分:3)
.hover()
方法会为mouseenter
和mouseleave
事件绑定处理程序。您可以使用它在鼠标位于元素中时简单地将行为应用于元素。
但是,如果您使用mouseover
和mouseout
事件,则当鼠标移入和移出元素及其后代时会触发这些事件。
有关您示例的替代尝试,请参阅http://jsfiddle.net/5yQY5/。
答案 1 :(得分:1)
改为使用mouseover和mouseout事件
$(function() {
$('div').on('mouseover', function(e){
e.stopPropagation();
$(this).addClass('my-bg');
}).on('mouseout', function(e){
$(this).removeClass('my-bg');
})
});
演示:Fiddle
注意:没有必要遍历每个div,然后为每个div添加事件处理程序,您只需调用$('div').hover(...)
,它将为所有div注册hover
处理程序
答案 2 :(得分:1)
您需要查找目标DOM
是否为child
。
示例强>
$(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
}
});