gpt4 book ai didi

javascript - 检查光标是否在元素的父元素内

转载 作者:搜寻专家 更新时间:2023-11-01 04:16:29 27 4
gpt4 key购买 nike

我有这个html

<div class='parent'> 
<div class='child'></div>
</div>

我想向 parent 元素添加 mouseover 和 mouseout 事件,但是,问题是当光标悬停在 child 元素上时,它会触发 mouseout 事件,尽管它实际上仍在 中>parent 元素。我如何避免这种情况,让 mouseout 事件仅在光标离开 parent 项目时触发。

$(body).on('mouseover', '.parent' , function(){ /* do somthing */}); 
$(body).on('mouseout', '.parent' , function(){ /* do another somthing */});

最佳答案

使用 mouseentermouseleave 而不是 mouseovermouseout 这将解决您的问题。

$(document).on('mouseenter', '.parent' , function(){
console.log("Mouse Enter");
});
$(document).on('mouseleave', '.parent' , function(){
console.log("Mouse Leave");
});

不要使用stopPropagation() 因为The Dangers of Stopping Event Propagation .

Demo

关于javascript - 检查光标是否在元素的父元素内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410112/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com