tio*_*chi 3 html javascript css jquery jquery-events
我有一个父div,高度= 100px,小于子div,高度= 200px.
当我在父div上附加jquery mouseenter时,即使我将指针悬停在child上,事件也会触发(将鼠标悬停在扩展父级高度的child部分上).
有谁能解释一下?
$(document).ready(function() {
$(".parent").mouseover(function(e) {
console.log(e.target);
});
$(".child").mouseover(function(e) {
console.log(e.target);
});
$(".grandchild").mouseover(function(e) {
console.log(e.target);
});
});Run Code Online (Sandbox Code Playgroud)
.parent {
background-color: green;
height: 50px;
}
.child {
background-color: red;
height: 100px;
}
.grandchild {
background-color: blue;
height: 200px;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="child">
<div class="grandchild">
Test
</div>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
- 更新 - 起初我不清楚究竟是什么问题.现在我想我明白了(我更新了代码).
假设我们有一个父div width=100px和height=100px.
然后我们有一个孩子div width=200px和height=200px(比父母更大的面积).
当我将鼠标悬停在子节点上(但尚未悬停在父节点上)时,浏览器会计算指针也在父节点上,尽管它没有.
因此,如果我在子项和父项上都有一个处理程序,它们将在我仅输入子div时触发.
谢谢.
您可以阻止事件从子项传播到父项,因此当您在子项上时,它不会在父项上触发:
$(".child").mouseover(function(e) {
e.stopPropagation();
});
Run Code Online (Sandbox Code Playgroud)