直接在.style
对象上设置样式属性将需要使用驼峰式
命名作为属性键,而不使用短横线
命名;如果需要设置更多的内联样式属性,则可以通过设置.style.cssText
属性,以更加高效的方式进行设置 。
const el = document.createElement('div')
el.style.backgroundColor = 'red'
// 或者
el.style.cssText = 'background-color: red'
// 或者
el.setAttribute('style', 'background-color: red')
cssText 的本质就是设置 HTML 元素的 style 属性值, but 给cssText设置后原先的css样式被清掉了
<div id="d1">煮一壶生死悲欢祭少年郎</div>
<script>
document.getElementById("d1").style.cssText = "color:red; font-size:13px;";
console.log(document.getElementById("d1").style.cssText);
// color: red; font-size: 13px;
</script>
如果这种设置内联样式过于繁琐,还可以考虑将.style
与Object.assign()
一起使用,以一次设置多个样式属性。
const el = document.createElement('div');
Object.assign(el.style, {
backgroundColor: "red",
margin: "25px"
})
使用obj.className来修改样式表的类名
el.className = "class-one class-two";
el.setAttribute("class", "class-one class-two");
更多精彩 请移步:http://by.wlgzs.club:8082/articles/2019/12/04/1575461558363.html