尝试使用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>
两个原因:
- 您不是在调用
myFunction
,而是在定义它 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
规则集。
您可以使用insertRule
或addRule
将规则动态添加到样式表中。
请查看"用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>