简体   繁体   English

带有媒体查询的Javascript菜单切换

[英]Javascript Menu toggle with Media Queries

How do I remove an event listener and class from an element in relation to a media query. 如何从与媒体查询相关的元素中删除事件侦听器和类。 I have been fiddling around with this, but nothing seems to work. 我一直在摆弄这个,但是似乎没有任何效果。 It works fine on moblie, but when I re-size the screen to become larger the 'menu-show' class is still there. 在moblie上它可以正常工作,但是当我调整屏幕尺寸使其更大时,“菜单显示”类仍然存在。

How would I use this with removeEventListener , it did not seem to work for me. 我如何将它与removeEventListener一起使用,它似乎对我不起作用。

function showMobileOptions(x) {
  if (x.matches) { 
      filters.forEach(filter => filter.addEventListener('click', function(){
        filter.querySelector('.menu-list').classList.toggle("menu-show");
        filter.querySelector('.menu-list').classList.toggle("toggle-close");
      }))
    } else {
      //remove event listener + '.menu-show' from all items
     filters.forEach(filter, function(){
      filter.querySelector('.menu-list').classList.remove("menu-show");
      filter.querySelector('.menu-list').classList.remove("toggle-close");
  });
  }
}

const x = window.matchMedia("(max-width: 768px)")
showMobileOptions(x)
x.addListener(showMobileOptions)

Use it like this 这样使用

filter.removeEventListener('click');

Best practice is to create a function for what you do when click fire, and then use the remove 最佳做法是为点击触发时要执行的操作创建一个函数,然后使用删除

filter.removeEventListener('click',myClickFunction);

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

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