![](/img/trans.png)
[英]jQuery + CSS: How to detect the first “move out” of cursor out of an element?
[英]How to detect if mouse cursor is out of element?
当我单击文档时,我有一个运行的侦听器。
document.addEventListener('click', print);
function print(element)
{
doSomething();
}
它会创建div id = panel,在其中打印一些信息。
当我运行打印功能时,我想检测是否在div#panel之外单击(该面板在我第二次单击时存在)。
我不希望使用mouseout事件侦听器,因为当事件单击已经触发时,使用侦听器进行鼠标移动是多余的。
如何检测我何时从div#panel中单击?
您可以检查jQuery click
事件的target
,它是哪个元素:
$(document).click(function(e) {
var target = $(e.target);
if( !target.is("#panel") && target.closest("#panel").length === 0 ) {
// click was not on or inside #panel
}
});
您的事件处理程序将传递一个事件对象,而不是元素。 由于您正在监听click事件,因此该事件的类型为MouseEvent,并且该事件对象将具有target属性,您可以使用该属性检查目标元素是否与所需元素匹配。
function handler(event) {
if (event.target == document.getElementById("panel")) {
// Do stuff
}
}
document.addEventListener('click', handler);
编辑:由于您自己的代码片段不使用jQuery,所以我故意给了香草JS答案。 但是jQuery不会改变任何东西,因为它的事件处理API几乎只是JS的薄包装。
我只是使用点击事件。 这里是
var elem=document.getElementById("elem");
var rects=elem.getBoundingClientRect();//get the bounds of the element
document.addEventListener('click', print);
function print(e)
{
//check if click position is inside or outside target element
if(e.pageX<= rects.left +rects.width && e.pageX>= rects.left && e.pageY<= rects.top +rects.height && e.pageY>= rects.top){
console.log("Inside element");
}
else{
console.log("Outside element");
}
}
JS Bin链接: https : //jsbin.com/pepilehigo/edit? html,js,console, output
仅使用javascript的另一种方法是:
function print(evt) { if (!(evt.target.tagName == 'DIV' && evt.target.classList.contains('myDiv'))) { var div = document.createElement('div'); div.classList.add('myDiv'); div.textContent="new div"; document.body.appendChild(div); } } window.onload = function() { document.addEventListener('click', print); }
.myDiv { border:1px solid green; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.