[英]How do I know if a mouse pointer is over a particular element on the page?
当然,借助JavaScript。
最简单的方法是处理元素的onmouseover
和onmouseout
事件:
element.onmouseover = function (e)
{
e = e || window.event;
alert("You moused over "+element.outerHTML);
}
element.onmouseout = function (e)
{
e = e || window.event;
alert("You moused out of "+element.outerHTML);
}
如果元素是在这些坐标处最顶层的元素,则也可以使用document.elementFromPoint(x, y)
:
var mouseX = 0, mouseY = 0;
document.documentElement.onmousemove = function (e)
{
e = e || window.event;
mouseX = e.clientX;
mouseY = e.clientY;
}
function getElementUnderMouse()
{
return document.elementFromPoint(mouseX, mouseY);
}
显然,如果您有某些元素阻止onmousemove
事件的传播/冒泡, onmousemove
鼠标悬停在这些元素上时,鼠标位置可能不正确。
触发onMouseover,onMouseout事件。
在下面的示例中,如果将鼠标悬停在div上,它将变为蓝色。
如果将onmouseover放置到完整的BODY上,则可以检查条件(ID,className,tagName等)是否要对要覆盖的元素执行操作。
<html>
<head>
<title>so</title>
</head>
<body>
<div>div 1</div>
<div>div 2</div>
<div>div 3</div>
<script>
document.body.onmouseover = function(ev){
var elm = ev.target || ev.srcElement;
if(elm.tagName === 'DIV'){
elm.style.backgroundColor = "#DEF";
}
};
</script>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.