获取使用像calc这样的表达式的CSS变量的计算值

时间:2019-05-21 00:49:49

标签: javascript css css-variables

在JavaScript中,您可以使用getPropertyValue(property)获得CSS变量的值。此函数对于检索在:root块中声明的变量很有用。

:root {
    --example-var: 50px;
}

但是,如果此变量表达式包含类似calc的函数,则即使使用getPropertyValuegetComputedStyle调用也会以文本形式而不是计算形式返回该表达式。

:root {
    --example-var: calc(100px - 5px);
}

如何获取使用calc之类的CSS函数的CSS变量的计算值?

请参见以下示例:

let div = document.getElementById('example');
console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
:root {
  --example-var: calc(100px - 5px);
}
<div id='example'></div>

3 个答案:

答案 0 :(得分:3)

从技术上讲,您不能,因为计算值不是静态的,并且将取决于其他属性。在这种情况下,这是微不足道的,因为我们正在处理像素值,但请设想一下您将拥有百分比值的情况。百分比是相对于其他属性的,因此我们无法将其与var()一起使用才能进行计算。如果我们使用emch等单位,则逻辑相同

这是一个简单的例子来说明:

let div = document.getElementById('example');
console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
console.log(window.getComputedStyle(div).getPropertyValue('font-size'))
console.log(window.getComputedStyle(div).getPropertyValue('width'))
console.log(window.getComputedStyle(div).getPropertyValue('background-size'));
:root {
  --example-var: calc(100% + 5px - 10px);
}
#example {
  font-size:var(--example-var);
  width:var(--example-var);
  background-size:var(--example-var);
}
<div id='example'>some text</div>

重要的是要注意最后一种情况,即结合百分比和像素值时,背景尺寸具有特殊的行为。您可以清楚地看到,浏览器甚至都不会计算5px - 10px,只有在使用var()之后才会这样做。


如果您知道calc()仅与像素值一起使用,则可以简单地将其应用于任何属性并读取它。之所以会起作用,是因为该计算值将始终以与该属性相同的方式求值:

let div = document.getElementById('example');
console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
console.log(window.getComputedStyle(div).getPropertyValue('font-size'))
console.log(window.getComputedStyle(div).getPropertyValue('width'))
console.log(window.getComputedStyle(div).getPropertyValue('background-size'));
console.log(window.getComputedStyle(div).getPropertyValue('background-color'));
:root {
  --example-var: calc(100px - 10px);
  --test:var(--example-var)
}
#example {
  font-size:var(--example-var);
  width:var(--example-var);
  background-size:var(--example-var);
  background-color:var(--example-var);
}
<div id='example'></div>

当然,您需要确保考虑一个期望像素值的属性,否则您将获得无效的值(例如上例中的背景)。

答案 1 :(得分:1)

将值(以编程方式)分配给某些不动产时将计算值:

const div = document.getElementById('example');
div.style.width = 'var(--example-var)';
console.log(window.getComputedStyle(div).getPropertyValue('width'));
:root {
  --example-var: calc(100px - 5px);
}
<div id='example'></div>

答案 2 :(得分:1)

一种古怪的方法是添加


:root {
  --example-var: calc(100px - 5px);
}

#var-calculator {
    // can be fetched through .getBoundingClientRect().width
    width: var(--example-var); 

    // rest of these just to make sure this element
    // does not interfere with your page design.
    opacity: 0;
    position: fixed;
    z-index: -1000;
}


 <custom-element>
  <div id="var-calculator"></div>
</custom-element>


const width = document.getElementById('var-calculator').getBoundingClientRect().width

我不知道这是否适用于您的用例,但我刚刚对其进行了测试,并且可以使用。

相关问题