原生 JS 调整样式方式有 3 种。
element.style
- 属性需要使用驼峰形式
!important权重无效
document.getElementById("box").backgroundColor = "red" // !important 无作用,下面两句是等效的 document.getElementById("box").style.color = "red !important" document.getElementById("box").style.color = "red"
【注意】这里使用 !important 权重是无效的
element.style.cssText
cssText 即所有的样式文本
- 可以一次修改多个样式属性
- 注意直接赋值会替换原来的
cssText - 可以添加
!important
// 原来的样式会丢失 document.getElementById("box").style.cssText = "color: red;font-size: 14px;" // 在原来样式的基础上添加新的样式 document.getElementById("box").style.cssText += "background-color: green;"
有什么区别
cssText适合用于批量修改,使页面只进行一次页面重绘- 在使用
!important权重的时候,只能使用cssText,style不能生效
element.setAttribute()
setAttribute() 方法可以设置元素的属性,当然也可以设置 style 属性。
document.getElementById("box").setAttribute("style","color:red;") // 配合 getAttribute(), 在原来样式基础上添加 document.getElementById("box").setAttribute("style", document.getElementById("box").getAttribute("style") + "color:red;")
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215982.html原文链接:https://javaforall.net
