如何在鼠标按下后停止“mousemove”事件?

问题描述 投票:0回答:3

我想在mousedown事件和mousemove上创建一个滑动幻灯片,但在mouseup我想停止mousemove事件。

slide.addEventListener("mousedown", e => {
  console.log(e.clientX);
});

slide.addEventListener("mousemove", function move(e) {
  //  do Somthing
});

slide.addEventListener("mouseup", function stop(e) {
  //  stop the mousemove event
});
javascript html
3个回答
1
投票

尝试在需要时添加和删除侦听器:

function move(e) {
  //  do Somthing
}

slide.addEventListener("mousedown", e => {
  console.log(e.clientX);
  slide.addEventListener("mousemove", move);
});

slide.addEventListener("mouseup", function stop(e) {
  slide.removeEventListener("mousemove", move);
});

0
投票

在通用范围中使用标志。将其设置为mousedown中的true和mouseup中的false。在mousemove中检查它

var pressing = false;

slide.addEventListener("mousedown", e => {
  pressing = true;
});

slide.addEventListener("mousemove", function move(e) {
  if (pressing) {
    // do something only if mouse button is being pressed
  }
});

slide.addEventListener("mouseup", function stop(e) {
  pressing = false;
});

-2
投票

为什么不删除事件监听器?

slide.addEventListener("mouseup", function stop(e) {
  slide.removeEventListener("mousemove", function move(e) {});
});
© www.soinside.com 2019 - 2024. All rights reserved.