You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现仅在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 16:39:04