直接在.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