如何在JavaScript MatchMedia上切换事件监听器

时间:2019-09-07 00:30:43

标签: javascript media-queries addeventlistener

我需要知道如何在屏幕小于700px时切换事件监听器,而当屏幕大于700px时事件监听器将被删除

function myFunction(x) {
  if (x.matches) { // If media query matches
    document.getElementById("resources").addEventListener("click", function() {
      alert("media worked")
    })
  } else {
    document.getElementById("resources").removeEventListener("click", function() {
      alert("media worked")
    })
  }
}

var x = window.matchMedia("(max-width: 979px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
h1 {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <h1 id="title">abrir y cerrar</h1>
  <button id="resources">click to toggle</button>
</body>

</html>

2 个答案:

答案 0 :(得分:2)

如果要使用removeEventListener,则需要使用命名函数,因为要删除的函数必须与添加的函数相同。

function clickHandler() {
  alert("media worked");
}

function myFunction(x) {
  if (x.matches) { // If media query matches
    document.getElementById("resources").addEventListener("click", clickHandler)
  } else {
    document.getElementById("resources").removeEventListener("click", clickHandler)
  }
}

var x = window.matchMedia("(max-width: 979px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
h1 {
  color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <h1 id="title">abrir y cerrar</h1>
  <button id="resources">click to toggle</button>
</body>

</html>

答案 1 :(得分:1)

Barmar 为您的代码问题给出了正确的答案。但是我仍然想添加它以表明这是一种可能性。

例如,您可以使用CSS通过pointer-events属性禁用对元素的点击。

var links = document.querySelectorAll('a');

function onClick(event) {
  console.log(event);
  event.preventDefault();
}

links.forEach(function(link) {
   link.addEventListener('click', onClick);
});
.events-none {
  pointer-events: none;
}
<a href="https://stackoverflow.com">Without pointer-events: none</a>
<a href="https://stackoverflow.com" class="events-none">With pointer-events: none</a>