通过Javascript访问CSS计算变量

时间:2017-07-23 17:22:24

标签: javascript css css-variables

在CSS中使用calc() ulated属性时,是否可以通过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访问最终的计算值?

1 个答案:

答案 0 :(得分:0)

我能想到的一个hack是将值应用于某些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作为结果。但这有点像hacky,所以找到一些直接访问变量计算值的方法会很好。无论如何它都有效。

请参阅my CodePen的工作代码。