尝试使用 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
将规则动态添加到样式表中。
请查看 David Walsh 的 “使用 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>