常見的使用 JS 來動態操作 css方法,你應該瞭解這些

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

如果這種設置內聯樣式過於繁瑣,還可以考慮將.styleObject.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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章