简体   繁体   English

JavaScript - window.matchMedia 未触发的事件侦听器

[英]JavaScript - Event listener with window.matchMedia not triggering

I've panned through countless solutions to this problem and none of them have fixed my issue.我已经为这个问题寻找了无数的解决方案,但没有一个解决了我的问题。 I very simply have a navigation bar, which, when on a mobile browser, disappears and becomes replaced with a button, whose function is to show and hide the navigation bar.我非常简单地有一个导航栏,当在移动浏览器上时,它会消失并替换为一个按钮,其功能是显示和隐藏导航栏。

Now, I want my listener to, when the window is shrunk, show the button and hide the navigation bar.现在,我希望我的听众在窗口缩小时显示按钮并隐藏导航栏。 When the window is expanded, the button should be hidden and the navigation bar should be shown.当窗口展开时,按钮应该隐藏,导航栏应该显示。 The button is working as it should be, since the media query doesn't affect it.该按钮正常工作,因为媒体查询不会影响它。 My listener appears to not run at all, except when the page is reloaded.我的监听器似乎根本没有运行,除非重新加载页面。

My script is contained inside of a PHP header which is included at the beginning of all my pages.我的脚本包含在 PHP 标头中,该标头包含在我所有页面的开头。 Here's what I've got:这是我所拥有的:

Media Query Listener (contained in header.php code)媒体查询监听器(包含在 header.php 代码中)

// ... navbar code, opening script tag, yadda yadda
function mediaQueryCheck(inputQuery) {
    var content = document.getElementById("navigation");
    if (inputQuery.matches) {
        // it matches
        content.style.display = "none";
    } else {
        // it does not match
        content.style.display = "block";
    }
}
var mobileQuery = window.matchMedia("screen and (max-width: 638px)");
mediaQueryCheck(mobileQuery);
mobileQuery.addEventListener(mediaQueryCheck);
// closing script tag

The element #navigation is a div element containing the navigation bar.元素#navigation是一个包含导航栏的div 元素。 I will provide any other relevant code, if necessary.如有必要,我将提供任何其他相关代码。

使用addListener代替addEventListener解决了该问题。

for whoever needs another solution:对于需要其他解决方案的人:
you may use this function:你可以使用这个功能:

function getWidth() {
  var maxWidth = Math.max(
        document.body.scrollWidth,
        document.documentElement.scrollWidth,
        document.body.offsetWidth,
        document.documentElement.offsetWidth,
        document.documentElement.clientWidth
   );
   console.log(maxWidth); // for testing only
   if(maxWidth === 776){
       //do sth
   }
   if(maxWidth === 992){
       //do sth
   }
   return maxWidth;
}
window.addEventListener("resize", getWidth);

now you have the width of the screen all the time现在你一直拥有屏幕的宽度
this is just another way of doing things... you may wanna use whatever serves your purpose.这只是另一种做事方式……您可能想使用任何符合您目的的方法。

You have to check it every time, when window is resized. 调整窗口大小时,您每次都要检查一次。

 window.addEventListener('resize', function(){ mediaQueryCheck(mobileQuery); }); 

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

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