如何检测鼠标何时远离元素

时间:2018-04-24 02:16:12

标签: javascript

鼠标在元素上移动时会触发mousemove。如何检测鼠标何时移动到元素外?换句话说,除了代码段中的div之外,页面上的任何位置。当鼠标离开元素时鼠标离开但不会触发。

const div = document.querySelector('div');

div.addEventListener('mousemove', function() {
    document.body.classList.add('mouse-moving');
 });
div {
  height: 200px;
  width: 300px;
  background-color: red;
}
.mouse-moving {
  background-color: green;
}
<div></div>

2 个答案:

答案 0 :(得分:3)

您可以使用onmouseover和onmouseout

const div = document.querySelector('div');

div.onmouseover = ()=> document.body.classList.add('mouse-moving');

 div.onmouseout = ()=> document.body.classList.remove('mouse-moving');
div {
  height: 200px;
  width: 300px;
  background-color: red;
}
.mouse-moving {
  background-color: green;
}
<div></div>

答案 1 :(得分:2)

您可以将mousemove事件监听器添加到document,并检查事件目标是否是您的div:

&#13;
&#13;
const div = document.querySelector('div');

document.addEventListener('mousemove', function(e) {
    if(e.target !== div) {
        div.textContent = "outside the div (" + e.clientX + ", " + e.clientY + ")";
    } else {
        div.textContent = "inside the div (" + e.clientX + ", " + e.clientY + ")";
    }
});
&#13;
div {
  height: 200px;
  width: 300px;
  background-color: red;
}
&#13;
<div></div>
&#13;
&#13;
&#13;

注意:如果div包含其他元素,则测试无法正常工作。你必须检查一个目标的祖先是否是你的div:

document.addEventListener('mousemove', function(e) {
    var elm;
    for(elm = e.target; elm && elm !== div; elm = elm.parentElement)
        ;

    if(elm === div) {
        // inside div
    } else {
        // outside div
    }
});

&#13;
&#13;
const div = document.querySelector('div'),
      result = document.querySelector("#result");

document.addEventListener('mousemove', function(e) {
    var elm;
    for(elm = e.target; elm && elm !== div; elm = elm.parentElement)
        ;

    if(elm === div) {
        result.textContent = "inside the div (" + e.clientX + ", " + e.clientY + ")";
    } else {
        result.textContent = "outside the div (" + e.clientX + ", " + e.clientY + ")";
    }
});
&#13;
div {
  height: 200px;
  width: 300px;
  background-color: red;
}

div > div {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
&#13;
<span id="result"></span>
<div>
  <div></div>
  <div></div>
</div>
&#13;
&#13;
&#13;

此外,如果div的孩子在其边界之外(由于某种绝对定位或某种原因),上述方法无法工作,您必须检查鼠标坐标是否为在div的边界矩形内。