繁体   English   中英

将鼠标悬停在矩形上时,如何让 cursor 的坐标跟随 cursor?

[英]How to let the coodinates of the cursor follow the cursor when hovering over a rectangle?

以下代码始终显示cursor下方的cursor的坐标:

 function showCoords(e) { var x = event.clientX; var y = event.clientY; var coor = "(" + x + ", " + y + ")"; document.getElementById("box").innerHTML = coor; var bx = document.getElementById("box"); bx.style.left = e.pageX - 50; bx.style.top = e.pageY + 20; } function clearCoords() { document.getElementById("box").innerHTML = ""; }
 div.relative { position: relative; width: 400px; height: 300px; border: 1px solid black; } div.abs { position: absolute; top: 100px; right: 50px; width: 200px; height: 100px; background-color: yellow; }
 <body onmousemove="showCoords(event)"> <div class="relative"> <div class="abs" onmousemove="showCoords(event)" onmouseout="clearCoords()"></div> </div> <div id="box" style="width:100px; height:30px; position:absolute"></div> </body>

当鼠标指针悬停在黄色矩形上时,我只希望坐标可见。 如果我将<body onmousemove="showCoords(event)">更改为<body> ,坐标将永远不可见。 如何让坐标仅在悬停在黄色矩形上时可见?

onmousemove侦听器从正文移动到您要侦听的元素 - 在本例中为div.abs

我建议不要使用onmousemove属性,而建议使用完全 javascript 解决方案 - 只是为了将 javascript-y 的东西放在一起。 像(未经测试)

var listenOn = document.querySelector(".abs");
listenOn.addEventListener("mousemove", ShowCoords);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM