簡體   English   中英

我如何設置這個 removeEventListener 的參數?

[英]how can i set this removeEventListener's param?

我正要制作一些旋轉程序(通過鼠標單擊和拖動來工作)但是“removeEventListener”不起作用。 你能解釋一下它是如何工作的嗎?為什么它不起作用?

這是我在這里的第一個問題,所以如果你發現這個問題有任何問題,我會很樂意接受。

<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);

});

我試圖改變這部分。 target -> 包裝和 removeEventListener 的參數到另一個。 但這些都不起作用

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

捕獲/使用捕獲標志必須匹配才能刪除偵聽器。 由於您對mousedown甚至偵聽器使用了 true ,因此您還必須使用 true 來刪除事件偵聽器:

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

有關詳細信息,請參閱文檔: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener#matching_event_listeners_for_removal

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM