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>
答案 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:
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;
注意:如果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
}
});
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;
此外,如果div的孩子在其边界之外(由于某种绝对定位或某种原因),上述方法无法工作,您必须检查鼠标坐标是否为在div的边界矩形内。