CSSStyleDeclaration: setProperty() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

CSSStyleDeclaration.setProperty() 方法用於在 CSS 樣式宣告物件上設定屬性的新值。

語法

js
setProperty(propertyName, value)
setProperty(propertyName, value, priority)

引數

propertyName

一個字串,表示要修改的 CSS 屬性名(短橫線命名法)。

value 可選

一個字串,包含新的屬性值。如果未指定,則視為空字串。null 值與空字串("")的處理方式相同。

注意: value 不能包含 "!important",這應該使用 priority 引數來設定。

priority 可選

一個字串,允許將 CSS 優先順序設定為 important。僅接受下面列出的值:

  • "important"(不區分大小寫),用於將屬性設定為 !important
  • ""undefinednull,用於移除存在的 !important 標誌。

任何其他值都會導致方法提前返回,並且不發生任何更改(除非 value 為空,在這種情況下,無論 priority 值如何,都會移除該屬性)。例如,false 不是一個有效的優先順序值。

返回值

無(undefined)。

異常

NoModificationAllowedError DOMException

如果屬性或宣告塊是隻讀的,則丟擲此錯誤。

替代用法

如果可以省略 priority,JavaScript 有一種特殊的更簡單的語法來在樣式宣告物件上設定 CSS 屬性。

js
style.cssPropertyName = "value";

示例

設定盒模型屬性

在這個示例中,我們有三個按鈕,按下它們可以動態地將我們的盒模型段落的邊框、背景顏色和文字顏色更改為隨機值(請參閱本節末尾的即時示例)。

MDN 的 即時示例 基礎架構將示例中的所有 CSS 塊合併到一個具有 css-output ID 的內聯樣式中,因此我們首先使用 document.getElementById() 來查詢該樣式表。

然後,我們迴圈遍歷在 stylesheet.cssRules 找到的陣列中包含的不同的規則。對於每條規則,我們檢查其 CSSStyleRule.selectorText 是否等於選擇器 .box p,這是我們想要的。

如果是,我們將對該 CSSStyleRule 物件的引用儲存在一個變數中。然後,我們使用三個函式為相關屬性生成隨機值,並用這些值更新規則。在每種情況下,都透過 setProperty() 方法完成,例如 boxParaRule.style.setProperty('border', newBorder);

HTML

html
<div class="controls">
  <button class="border">Border</button>
  <button class="bgcolor">Background</button>
  <button class="color">Text</button>
</div>
<div class="box">
  <p>Box</p>
</div>

CSS

css
html {
  background: orange;
  font-family: sans-serif;
  height: 100%;
}

body {
  height: inherit;
  width: 80%;
  min-width: 500px;
  max-width: 1000px;
  margin: 0 auto;
}

.controls {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

div button {
  flex: 1;
  margin: 20px;
  height: 30px;
  line-height: 30px;
}

.box {
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100% - 70px);
}

.box p {
  width: 50%;
  text-align: center;
  font-weight: bold;
  font-size: 40px;
  height: 150px;
  line-height: 150px;
  background: red;
  border: 5px solid purple;
  color: white;
  transition: all 1s;
}

JavaScript

js
const borderBtn = document.querySelector(".border");
const bgColorBtn = document.querySelector(".bgcolor");
const colorBtn = document.querySelector(".color");
const box = document.querySelector(".box");

function random(min, max) {
  const num = Math.floor(Math.random() * (max - min)) + min;
  return num;
}

function randomColor() {
  return `rgb(${random(0, 255)} ${random(0, 255)} ${random(0, 255)})`;
}

// Find the inline stylesheet generated for MDN live samples
const stylesheet = document.getElementById("css-output").sheet;

const boxParaRule = [...stylesheet.cssRules].find(
  (r) => r.selectorText === ".box p",
);

function setRandomBorder() {
  const newBorder = `${random(1, 50)}px solid ${randomColor()}`;
  boxParaRule.style.setProperty("border", newBorder);
}

function setRandomBgColor() {
  const newBgColor = randomColor();
  boxParaRule.style.setProperty("background-color", newBgColor);
}

function setRandomColor() {
  const newColor = randomColor();
  boxParaRule.style.setProperty("color", newColor);
}

borderBtn.addEventListener("click", setRandomBorder);
bgColorBtn.addEventListener("click", setRandomBgColor);
colorBtn.addEventListener("click", setRandomColor);

結果

規範

規範
CSS 物件模型 (CSSOM)
# dom-cssstyledeclaration-setproperty

瀏覽器相容性