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

标签 javascript jquery

我有这个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/

相关文章:

javascript - 我们如何使用 Grid 配置 Kendo-UI ComboBox。

javascript - jQuery:获取 JSON 请求响应并将其显示在当前 html 页面下

javascript - 诗农.js : avoid stubbing twice

jquery - table.row 不是函数

javascript - window.onbeforeunload 在第二页中不起作用

javascript - 如何突出显示 HTML5 表格中选定/单击的单元格

javascript - 将动态生成的字符串从 View 传递到 Controller

javascript - 为什么 Javascript RegExp 有一个双对象原型(prototype)

javascript - 安装网络音频 API

jquery - 菜单项下的箭头