代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQ--mouseenter测试</title>
<style>
*{margin: 0; padding: 0; color: #fff;}
div{width: 100px; height: 100px; padding-top: 20px; background: green; margin: 100px auto;}
p{width: 150px; height: 50px; background: red;}
</style>
<script src="jquery.js"></script> <!-- 1.9.0版 -->
</head>
<body>
<div id="d">
<p>子元素</p>
父元素
</div>
<script>
var a=0;
$(function(){
$('#d').mouseenter(function(){ /*#d,父元素,当mouseenter时背景变为黑色*/
$(this).css('background','#000');
});
$('#d p').mouseenter(function(){ /*#d p,子元素,当mouseenter时背景变为黑色*/
$(this).css('background','#000');
});
});
</script>
</body>
</html>
**当鼠标移入子元素时,我以为只有子元素的背景变成黑色,因为.mouseenter()不冒泡,但结果父、子两个元素都变成黑色了。
我不明白了,mouseenter不冒泡啊,那应该只有子元素背景变成黑色,怎么都变了?求讲解!**
1)mouseenter不冒泡是指,当以一个元素捕获到mouseenter事件后,不再通知其父元素,父元素也就不会处理mouseenter时间了
2)就问题中的2个mouseenter
似乎还是不好理解
那么我们就看下冒泡的mouseover是个什么样的表现
运行上面饿代码我们能看到,每次鼠标进入子元素触发mouseover事件,就会冒泡到其父元素,进入执行父元素的mouseover事件监听-显示的数字会增加
而换成mouseenter事件监听就不会发生这样的情况-显示的数字不增加
并且在子元素的mouseover的事件监听函数中阻止冒泡-stopPropagation,父元素的事件就不会被回调