[英]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.