简体   繁体   中英

how can i set this removeEventListener's param?

I was about to make some rotation programm (worked by mouse click & drag) but the 'removeEventListener' doesn't work. can u explain me how to work it and why doesn't it work?

And this is my first question in here so if u find any problems about this question, I'll gladly accept it.

<body>

    <div class="wrap">

        <div class="target">target</div>

    </div>
</body>
const html = document.querySelector("html");
const info = document.querySelector(".info");

const target = document.querySelector(".target");
const wrap = document.querySelector(".wrap");
let center = {
  x: target.getBoundingClientRect().left + target.clientWidth / 2,
  y: target.getBoundingClientRect().top + target.clientHeight / 2,
};

window.addEventListener("resize", () => {
  center = {
    x: target.getBoundingClientRect().left + target.clientWidth / 2,
    y: target.getBoundingClientRect().top + target.clientHeight / 2,
  };
});

const rotate = function () {
  target.addEventListener("mousemove", (e) => {
    const x = center.x - e.clientX;
    const y = center.y - e.clientY;

    const radian = Math.atan2(y, x);
    const degree = ((radian * 180) / Math.PI).toFixed(0);
    target.style.transform = "rotate(" + degree + "deg)";
  });
};

target.addEventListener("mousedown", rotate, true);

target.addEventListener("mouseup", () => {
  target.removeEventListener("mousedown", rotate, false);

});

I've tried to change this part. target -> wrap and removeEventListener's param to another one. But none of those worked

target.addEventListener("mouseup", () => {
  target.removeEventListener("mousedown", rotate, false);
});

The capture/ use capture falg must match to remove listener. Since you used true for your mousedown even listener you also must use true to remove event listener:

target.addEventListener("mouseup", () => {
    target.removeEventListener("mousedown", rotate, true);
});

See docs for more details: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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