简体   繁体   English

如何在 window.matchMedia 中添加 removeEventListener?

[英]How to add removeEventListener in window.matchMedia?

Here is my problem:这是我的问题:

I want to have an "addEventListener" click method only for browser size smaller than "400px".我只想为小于“400px”的浏览器提供“addEventListener”点击方法。 But when we resize the browser, I want to remove this method.但是当我们调整浏览器的大小时,我想删除这个方法。

The format of my code is below.我的代码格式如下。 If I grow up the browser over 400px I continue to have the method.如果我将浏览器长大超过 400 像素,我将继续使用该方法。 I want your help.我需要你的帮助。

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

"Calling removeEventListener() with arguments that do not identify any currently registered EventListener on the EventTarget has no effect." “使用 arguments 调用 removeEventListener() 并不能识别 EventTarget 上任何当前注册的 EventListener 无效。”

You define new version of card Function each time you call customFunctions so you can't detach it from element because is not the same function that you attach.您每次调用 customFunctions 时都定义新版本的卡 Function ,因此您不能将其与元素分离,因为与您附加的 function 不同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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