通过 Javascript 访问 CSS 计算变量



在CSS中使用calc()属性时,是否可以通过Javacsript访问它们的扩展(即实际计算(值?

例如,考虑以下 CSS:

:root {
--ratio: calc(16 / 9);
--width: 100px;
--height: calc(var(--width) / var(--ratio));
}

和Javascript:

const computedStyle = window.getComputedStyle(document.documentElement);
console.info(computedStyle.getPropertyValue('--height'));

人们希望看到56px被打印出来;相反,返回字符串"calc(var(--width) / var(--ratio))"

即使您尝试将其应用于某些 CSS 类属性并从类声明中读取,它也不会起作用:

.rectangle {
height: var(--height);
}

Javascript:

const rectangleClassDeclaration = /* find it through document.styleSheets */
console.info(rectangleClassDeclaration.style.getPropertyValue('height'));

控制台显示"var(--height)".

那么,有没有办法通过Javascript访问最终的计算值呢?

我能想到的一个技巧是将值应用于某个 DOM 元素,然后他们从中读取。

.CSS:

.rectangle {
height: var(--height);
}

.HTML:

<div class="rectangle"></div>

Javascript:

const rectangle = document.querySelector('.rectangle');
const computedStyle = window.getComputedStyle(rectangle);
console.info(computedStyle.getPropertyValue('height'));

然后你会看到56px结果。但这有点笨拙,所以最好找到一些直接访问变量计算值的方法。无论如何,它有效。

请参阅我的带有工作代码的代码笔。

最新更新