获取使用类似calc表达式的CSS变量的计算值
P粉111627787
P粉111627787 2023-10-25 09:39:36
0
2
923

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

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

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

: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>


P粉111627787
P粉111627787

全部回复(2)
P粉936509635

一种奇怪的方法是添加

: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

我不知道这是否适用于您的用例,但我刚刚测试过它并且它有效。

P粉838563523

从技术上讲,您不能,因为计算值不是静态的,并且将取决于其他属性。在这种情况下,这很简单,因为我们正在处理像素值,但想象一下您将拥有百分比值的情况。百分比是相对于其他属性而言的,因此在与 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>
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!