[英]How to change CSS media query styles dynamically using JavaScript?
我正在尝试为小于 700 像素的屏幕实现暗模式。 我为所有屏幕全局设置了主体背景,然后有 JS 设置间隔 function 会在一段时间后将主体背景颜色更改为白色。 @media only screen and (max-width: 700px) 有自己的背景黑色设置。 但由于设置的间隔 function,一段时间后它会变回白色。 所以请帮助我如何访问 CSS @media only screen 下的主体背景属性和(最大宽度:700px)以在设置间隔 function 内的某个时间后更改背景颜色。我正在寻找已经使用 JS 的 JavaScript 解决方案. 有没有办法在 JS function 中使用 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
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)";
}
*/
您可以使用 matchMedia API:
if (window.matchMedia("(max-width: 700px)").matches && window.matchMedia("(orientation: portrait)").matches) {
// your code
}
您只需输入与 CSS 中相同的 arguments
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.