简体   繁体   English

如果 window 大小发生变化,如何更新 window.matchMedia?

[英]How to update window.matchMedia if window size changes?

This function only works when the page gets reloaded:此 function 仅在页面重新加载时有效:

 if (window.matchMedia("(max-width: 700px)").matches) { $("html").css("background-color", "yellow"); } else { $("html").css("background-color", "red"); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But how can I additionally update it if the window size changes?但是,如果 window 大小发生变化,我该如何另外更新它?

This article didn't help me so far.到目前为止, 这篇文章对我没有帮助。 It's hard for me to find the best solution.我很难找到最佳解决方案。

You could set up the event handler using the addEventListener() method:您可以使用 addEventListener() 方法设置事件处理程序:

Window.addEventListener('resize', reportWindowSize);

function reportWindowSize() {
  var height = window.innerHeight;
  var width = window.innerWidth;
}

or或者

window.onresize = reportWindowSize;

Using jQuery just put it in a resize event handler and trigger the event also when page loads使用 jQuery 只需将其放入调整大小事件处理程序并在页面加载时也触发事件

$(window).resize(function(){    
    if (window.matchMedia("(max-width: 700px)").matches) {
      $("html").css("background-color", "yellow");
    } else {
      $("html").css("background-color", "red");
    }
}).resize()// trigger on page load

 function myFunction() { if (window.matchMedia("(max-width: 700px)").matches) { $("html").css("background-color", "yellow"); } else { $("html").css("background-color", "red"); } }; // Resize event window.addEventListener("resize", myFunction); // First load window.addEventListener("load", myFunction);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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