我有这个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 */});
最佳答案
使用 mouseenter
和 mouseleave
而不是 mouseover
和 mouseout
这将解决您的问题。
$(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 .
关于javascript - 检查光标是否在元素的父元素内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410112/