简体   繁体   English

如何使用 JavaScript 动态更改 CSS 媒体查询 styles?

[英]How to change CSS media query styles dynamically using JavaScript?

I am trying to implement a dark mode for only screens that are less than 700px.我正在尝试为小于 700 像素的屏幕实现暗模式。 I have body background set globally for all screens, then there is JS set interval function that will change the body background color to white after sometime.我为所有屏幕全局设置了主体背景,然后有 JS 设置间隔 function 会在一段时间后将主体背景颜色更改为白色。 @media only screen and (max-width: 700px) has its own background black set. @media only screen and (max-width: 700px) 有自己的背景黑色设置。 But because of the set interval function, it will change back to white after sometime.但由于设置的间隔 function,一段时间后它会变回白色。 So please help me how can I access the body background property under CSS @media only screen and (max-width: 700px) to change the background color after sometime inside the set interval function. I am looking for a JavaScript solution as already using JS.所以请帮助我如何访问 CSS @media only screen 下的主体背景属性和(最大宽度:700px)以在设置间隔 function 内的某个时间后更改背景颜色。我正在寻找已经使用 JS 的 JavaScript 解决方案. Is there any way to do it inside the JS function using CSS variable有没有办法在 JS function 中使用 CSS 变量

CSS CSS

body {       
    background: rgba(225,119,119,0.4);  
}

@media only screen and (max-width: 700px) and (orientation: portrait) {
    body {
        background: rgba(0,0,0,1); 
    }
}

JS JS

setInterval(function() {       
    document.body.style.background = "rgba(255,255,255,1)";
}, 292);

   /* 
   There inside the JS function I want to change body background for the css media query 
      ... 
      do I need if else conditions for this here
      like 
      if(max-width: 700px) 
      {
          document.body.style.background = "rgba(0,0,0,1)";
      } 
   */

You can make use of the matchMedia API:您可以使用 matchMedia API:

if (window.matchMedia("(max-width: 700px)").matches && window.matchMedia("(orientation: portrait)").matches) {
   // your code
}

You just have to enter the same arguments as in the CSS您只需输入与 CSS 中相同的 arguments

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

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