如何将JavaScript变量值添加到CSS变量中



尝试使用Window.innerWidth并将接收到的值加载到CSS变量中,但似乎不起作用。我做错了什么?

function myFunction() {
var w = window.innerWidth;

document.documentElement.style
.setProperty('--window', w);}
:root {
--window:0px;
}
div {

height: calc(var(--window) / 2);
background:red;

}
<div></div>

两个原因:

  1. 您不是在调用myFunction,而是在定义它
  2. window.innerWidth返回一个没有单位的数字(表示像素(。为了使其成为有效的height值,您应该添加px作为后缀

function myFunction() {
var w = window.innerWidth;
document.documentElement.style.setProperty('--window', `${w}px`);
}
myFunction();
:root {
--window: 0px;
}
div {
height: calc(var(--window) / 2);
background: red;
}
<div></div>

还有一件事你可能不知道:var()接受一个默认值。如果--window只使用一次,则可以将属性写为height: calc(var(--window, 0px) / 2);,并省略:root规则集。

您可以使用insertRuleaddRule将规则动态添加到样式表中。

请查看"用JavaScript将规则添加到样式表中">

// See: https://davidwalsh.name/add-rules-stylesheets
const addCSSRules = (sheet, selector, rules, index = 1) => {
if (typeof rules !== 'string') {
rules = Object.entries(rules).map(entry => entry.join(':')).join(';');
}
if ('insertRule' in sheet) {
sheet.insertRule(`${selector} {${rules}}`, index);
} else if ('addRule' in sheet) {
sheet.addRule(selector, rules, index);
}
}
const [ sheet ] = document.styleSheets;
addCSSRules(sheet, ':root', {
'--window': `${window.innerWidth}px`
});
:root {
--window: 0px;
}
div {
height: calc(var(--window) / 2);
background: red;
}
<div></div>

最新更新