原生JS设置CSS样式有多少方式

时间:2025-01-22 13:21:29

文章导航

      • 有什么区别


原生 JS 调整样式方式有 3 种。

  • 属性需要使用驼峰形式
  • !important 权重无效
document.getElementById("box").backgroundColor = "red"

// !important 无作用,下面两句是等效的
document.getElementById("box").style.color = "red !important"
document.getElementById("box").style.color = "red"

【注意】这里使用 !important 权重是无效的

cssText 即所有的样式文本

  • 可以一次修改多个样式属性
  • 注意直接赋值会替换原来的 cssText
  • 可以添加 !important
// 原来的样式会丢失
document.getElementById("box").style.cssText = "color: red;font-size: 14px;"

// 在原来样式的基础上添加新的样式
document.getElementById("box").style.cssText += "background-color: green;"

有什么区别

  • cssText 适合用于批量修改,使页面只进行一次页面重绘
  • 在使用 !important 权重的时候,只能使用 cssTextstyle 不能生效

()
setAttribute() 方法可以设置元素的属性,当然也可以设置 style 属性。

document.getElementById("box").setAttribute("style","color:red;")

// 配合 getAttribute(), 在原来样式基础上添加
document.getElementById("box").setAttribute("style", document.getElementById("box").getAttribute("style") + "color:red;")