搜尋

首頁  >  問答  >  主體

JavaScript 允許存取 CSS 自訂屬性(也稱為 CSS 變數)

如何使用 JavaScript(普通或 jQuery)來取得和設定 CSS 自訂屬性(透過樣式表中的 var(…) 存取的屬性)?

這是我不成功的嘗試:點擊按鈕會更改通常的 font-weight 屬性,但不會更改自訂 --mycolor 屬性:

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <style>
    body { 
      --mycolor: yellow;
      background-color: var(--mycolor);
    }
  </style>
</head>
<body>

  <p>Let's try to make this text bold and the background red.</p>
  <button onclick="plain_js()">Plain JS</button>
  <button onclick="jQuery_()">jQuery</button>

  <script>
  function plain_js() { 
    document.body.style['font-weight'] = 'bold';
    document.body.style['--mycolor'] = 'red';
  };
  function jQuery_() {
    $('body').css('font-weight', 'bold');
    $('body').css('--mycolor', 'red');
  }
  </script>
</body>
</html>

P粉420868294P粉420868294483 天前763

全部回覆(2)我來回復

  • P粉421119778

    P粉4211197782023-10-21 17:19:53

    原生解決方案

    取得/設定 CSS3 變數的標準方法.setProperty().getPropertyValue()

    如果您的變數是全域變數(在 :root 中宣告),您可以使用下列內容來取得和設定它們的值。

    // setter
    document.documentElement.style.setProperty('--myVariable', 'blue');
    // getter
    document.documentElement.style.getPropertyValue('--myVariable');

    但是,如果已使用 .setProperty() 設定了 var 的值,則 getter 只會傳回該值。 如果已通過CSS聲明設置,將返回undefined。在這個例子中檢查一下:

    let c = document.documentElement.style.getPropertyValue('--myVariable');
    alert('The value of --myVariable is : ' + (c?c:'undefined'));
    :root{ --myVariable : red; }
    div{ background-color: var(--myVariable); }
      <div>Red background set by --myVariable</div>

    為了避免這種意外行為,您必須在呼叫 .getPropertyValue() 之前使用 getCompulatedStyle() 方法。 然後吸氣劑將如下所示:

    getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');

    在我看來,存取CSS變數應該更簡單、快速、直覺和自然...


    我個人的做法

    我實作了CSSGlobalVariables 一個小型(<3kb) javascript 幫助程序,它會自動檢測文件中所有活動的CSS 全域變數並將其打包到一個物件中,<3kb) javascript 帮助程序,它自动检测文档中所有活动的 CSS 全局变量并将其打包到一个对象中,以便更輕鬆地存取和操作< /strong>.

    // get the document CSS global vars
    let cssVar = new CSSGlobalVariables();
    // set a new value to --myVariable
    cssVar.myVariable = 'red';
    // get the value of --myVariable
    console.log( cssVar.myVariable );

    應用於物件屬性的任何變更都會自動轉換為 CSS 變數。

    可用https://github.com/colxi/ css-全域變數

    回覆
    0
  • P粉863295057

    P粉8632950572023-10-21 14:23:27

    您可以使用document.body.style.setProperty('--name', 值);

    var bodyStyles = window.getComputedStyle(document.body);
    var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get
    
    document.body.style.setProperty('--foo-bar', newValue);//set

    回覆
    0
  • 取消回覆