【发布时间】:2025-12-24 19:30:10
【问题描述】:
我有一个 height=100px 的父 div,它小于 height=200px 的子 div。
当我在父 div 上附加 jquery mouseenter 时,即使我将指针悬停在子元素上(悬停在扩展父元素高度的子元素部分),事件也会触发。
谁能解释一下?
$(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);
});
});
.parent {
background-color: green;
height: 50px;
}
.child {
background-color: red;
height: 100px;
}
.grandchild {
background-color: blue;
height: 200px;
}
<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>
--更新-- 起初我不清楚到底是什么问题。现在我想我明白了(我更新了代码)。
假设我们有一个带有 width=100px 和 height=100px 的父 div。
然后我们有一个带有width=200px 和height=200px 的子div(比父级更大)。
当我将鼠标悬停在子级上时(但还没有在父级上),浏览器会计算出指针也在父级上,尽管它没有。
因此,如果我在子级和父级上都有一个处理程序,那么它们只会在我进入子 div 时触发。
谢谢。
【问题讨论】:
-
触发器?触发什么?请改进标题
-
我认为您应该更好地解释您想了解的内容。您是在问为什么当您将鼠标悬停在子对象上时会触发事件,还是希望事件仅在鼠标悬停在父对象而不是子对象上时触发?
-
@vsync 你是对的,我的标题是错误的。我改了。
标签: javascript jquery html css jquery-events