如何使用 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>
獲取/設置 CSS3 變量的標準方法是 .setProperty()
和 .getPropertyValue()
。
如果您的變量是全局變量(在 :root
中聲明),您可以使用以下內(nèi)容來獲取和設置它們的值。
// 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>
為了避免這種意外行為,您必須在調(diào)用 .getPropertyValue()
之前使用 getCompulatedStyle()
方法。
然后吸氣劑將如下所示:
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
在我看來,訪問CSS變量應該更加簡單、快速、直觀和自然......
我實現(xiàn)了 CSSGlobalVariables
一個小型 (以便更輕松地訪問和操作.
// 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 );
應用于對象屬性的任何更改都會自動轉(zhuǎn)換為 CSS 變量。
您可以使用document.body.style.setProperty('--name', value);
:
var bodyStyles = window.getComputedStyle(document.body); var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get document.body.style.setProperty('--foo-bar', newValue);//set