求助:实现跟随鼠标的XY坐标显示区块效果(附代码)
实现鼠标跟随区块并实时显示XY坐标
嘿,别发愁啦!我帮你把两段代码整合到一起,完美实现你想要的效果——一个跟着鼠标跑的区块,还能实时显示当前的XY坐标。下面是完整的可运行代码,我会顺便拆解关键部分,方便你理解:
<!DOCTYPE html> <html> <head> <style> /* 鼠标跟随区块的样式 */ #cursor-follower { position: absolute; display: none; /* 初始隐藏,鼠标移动后显示 */ width: 80px; height: 30px; background-color: rgba(0, 0, 0, 0.8); color: white; font-size: 14px; line-height: 30px; text-align: center; border-radius: 4px; pointer-events: none; /* 避免区块干扰鼠标事件 */ z-index: 9999; /* 确保区块在最上层 */ } </style> </head> <body> <!-- 用来显示坐标的区块 --> <div id="cursor-follower"></div> <script> // 获取DOM元素 const follower = document.getElementById('cursor-follower'); // 监听鼠标移动事件,同时处理位置更新和坐标显示 document.addEventListener('mousemove', function(e) { // 1. 获取当前鼠标的XY坐标 const x = e.clientX; const y = e.clientY; // 2. 更新跟随区块的位置(这里给了一点偏移,避免挡住鼠标) follower.style.left = `${x + 15}px`; follower.style.top = `${y + 15}px`; // 3. 更新区块内的坐标文本 follower.textContent = `X: ${x}, Y: ${y}`; // 4. 第一次移动鼠标时显示区块 if (follower.style.display === 'none') { follower.style.display = 'block'; } }); </script> </body> </html>
关键逻辑拆解:
- 样式部分:给跟随区块加了
pointer-events: none,这样鼠标不会被区块挡住,能正常触发页面其他元素的事件;z-index:9999保证它不会被其他内容盖住。 - JS部分:把获取坐标和更新区块位置的逻辑放到同一个
mousemove事件监听里——每次鼠标移动,我们同时拿到坐标、调整区块位置、更新显示的文本,一步到位。 - 初始显示:一开始区块是隐藏的,第一次鼠标移动时再显示它,避免页面加载后就出现空区块。
你可以直接把这段代码复制到HTML文件里打开试试,效果和你想要的一样!如果需要调整样式(比如颜色、大小、偏移量),直接改CSS里的属性就行啦。
内容的提问来源于stack exchange,提问作者antogd
相关产品推荐
相关产品推荐

