在 JavaScript 中,您可以使用 getPropertyValue(property)
獲取 CSS 變量的值。此函數(shù)對(duì)于檢索 :root
塊中聲明的變量很有用。
:root { --example-var: 50px; }
但是,如果此變量表達(dá)式包含類似 calc
的函數(shù),則 getPropertyValue
調(diào)用將以文本形式返回表達(dá)式而不是計(jì)算它,即使使用 getCompulatedStyle
時(shí)也是如此。
:root { --example-var: calc(100px - 5px); }
如何獲取使用 calc
等 CSS 函數(shù)的 CSS 變量的計(jì)算值?
請參閱下面的示例:
let div = document.getElementById('example'); console.log(window.getComputedStyle(div).getPropertyValue('--example-var'))
:root { --example-var: calc(100px - 5px); }
<div id='example'></div>
一種奇怪的方法是添加
: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
我不知道這是否適用于您的用例,但我剛剛測試過它并且它有效。
從技術(shù)上講,您不能,因?yàn)橛?jì)算值不是靜態(tài)的,并且將取決于其他屬性。在這種情況下,這很簡單,因?yàn)槲覀冋谔幚硐袼刂担胂笠幌履鷮碛邪俜直戎档那闆r。百分比是相對(duì)于其他屬性而言的,因此在與 var()
一起使用之前我們無法計(jì)算它。如果我們使用 em
、ch
等單位,則邏輯相同
下面是一個(gè)簡單的例子來說明:
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>