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

浏览器兼容性