如何在window.matchMedia中添加removeEventListener?

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

这是我的问题:

我想要一个仅适用于小于“400px”的浏览器尺寸的“addEventListener”点击方法。但是当我们调整浏览器大小时,我想删除这个方法。

我的代码格式如下。如果我的浏览器尺寸超过 400px,我会继续使用该方法。我需要你的帮助。

function customFunction(x) {

    var cardClick = document.getElementsByClassName("card");
    var inner = document.getElementsByClassName("card-inner");

    if (x.matches) {

        cardClick[0].addEventListener("click", cardFunction);

        function cardFunction() {
            // some code
            // inner[0].style......
        }

    } else {

        cardClick[0].removeEventListener("click", cardFunction);

    }
}

var x = window.matchMedia("(max-width: 400px)");
customFunction(x);
x.addListener(customFunction);
javascript addeventlistener removeeventlistener matchmedia
3个回答
1
投票

“使用不标识 EventTarget 上当前注册的任何 EventListener 的参数调用 removeEventListener() 没有任何效果。”

每次调用 customFunctions 时都会定义新版本的卡函数,因此您无法将其与元素分离,因为它与您附加的函数不同。

function cardFunction() {
   // some code
   // inner[0].style......
}

function customFunction(x) {

    var cardClick = document.getElementsByClassName("card");
    var inner = document.getElementsByClassName("card-inner");

    if (x.matches) {
        cardClick[0].addEventListener("click", cardFunction);

    } else {
        cardClick[0].removeEventListener("click", cardFunction);
    }
}

var x = window.matchMedia("(max-width: 400px)");
customFunction(x);
x.addListener(customFunction);
javascript

0
投票
x.removeListener(customFunction)

在此处查看示例:https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/removeListener


0
投票

对于那些因为无法从

matchMedia
中删除监听器而专门登陆这里的人,我想我应该添加一些细节。

这是错误的:

// Add listener
window
  .matchMedia(yourQuery)
  .addEventListener('change', yourHandlerFunction);

// Remove listener
window
  .matchMedia(yourQuery)
  .removeEventListener('change', yourHandlerFunction);

这才是正确的做法:

// Create the media matcher:
const mediaWatcher = window.matchMedia(yourQuery);

// Add the listener
mediaWatcher
  .addEventListener('change', yourHandlerFunction);

// Remove the listener
mediaWatcher
  .removeEventListener('change', yourHandlerFunction);
© www.soinside.com 2019 - 2024. All rights reserved.