如何实现仅在mousedown与mousemove同时触发时显示屏幕坐标
问题原因
removeEventListener方法要求移除时传入的回调函数,必须和绑定事件时传入的回调是同一个内存地址的引用。你的代码中绑定mousemove和移除mousemove时分别传入了两个不同的匿名函数,引用地址不匹配,所以事件监听不会被移除,鼠标松开后坐标仍然会持续更新。
修复方案
将mousemove的回调逻辑抽为独立的命名函数,绑定和移除时都使用这个函数即可。
修复后完整代码
JS 代码
let xPosition = document.getElementById("x") let yPosition = document.getElementById("y") // 抽离为独立命名函数,保证添加、移除事件时引用一致 function updateCoordinate(event) { xPosition.textContent = `X: ${event.screenX}` yPosition.textContent = `Y: ${event.screenY}` } addEventListener('mousedown', (e) => { console.log(e.type) moveMouse(e.type) }) addEventListener('mouseup', (e) => { moveMouse(e.type) }) function moveMouse(e) { if (e === 'mousedown') { addEventListener('mousemove', updateCoordinate) } if (e === 'mouseup') { removeEventListener('mousemove', updateCoordinate) console.log('move mouse event removed.') } }
CSS 代码
.coordinate-container { position: absolute; justify-content: center; align-items: center; display: flex; flex-direction: row; top: 0; left: 0; width: 150px; height: 150px; background-color: blue; } .coordinate-container #x, .coordinate-container #y { width: 100%; height: 75px; color: white }
HTML 代码
<body> <div class="coordinate-container"> <div id="x"></div> <div id="y"></div> </div> <script src="script.js"></script> </body>
内容的提问来源于stack exchange,提问作者tim_woods
相关产品推荐
相关产品推荐

