首頁  >  問答  >  主體

取得使用類似calc表達式的CSS變數的計算值

在 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粉111627787P粉111627787330 天前927

全部回覆(2)我來回復

  • P粉936509635

    P粉9365096352023-10-26 00:55:18

    一種奇怪的方法是添加

    
    :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

    我不知道這是否適用於您的用例,但我剛剛測試過它並且它有效。

    回覆
    1
  • P粉838563523

    P粉8385635232023-10-26 00:31:35

    從技術上講,您不能,因為計算值不是靜態的,並且將取決於其他屬性。在這種情況下,這很簡單,因為我們正在處理像素值,但想像一下您將擁有百分比值的情況。百分比是相對於其他屬性而言的,因此在與 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>

    回覆
    0
  • 取消回覆