動態修改樣式是前端交互的基礎能力。JS 操作樣式主要分兩條路:改 class 讓 CSS 生效,或者直接改行內 style。前者利於復用,後者勝在精準。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>樣式操作示例</title>
<style>
.fontSize { font-size: 20px; }
.fontWeight { font-weight: bold; }
</style>
</head>
<body>
<div id="div" class="fontSize fontWeight" style="color:red">div 實例文本</div>
<button onclick="changeStyle()">changeStyle()</button>
<script>
function changeStyle() {
var div = document.getElementById("div");
// 設置單個 class
// div.className = "fontSize";
// 追加 class
// div.className += " fontWeight";
// 刪除某個 class 樣式
// div.className = div.className.replace(/fontSize/, "");
// 刪除所有 class 樣式
// div.removeAttribute("class");
// 刪除 style 中的單個樣式
div.style.cssText = div.style.cssText.replace(/red/, "blue");
// 刪除 style 中的所有樣式
// div.style.cssText = "";
}
</script>
</body>
</html>
第一,className 是字符串,直接賦值會整體覆蓋原有類名,追加時記得補上空格,或用 classList.add()/classList.remove() 更安全。
第二,style.cssText 讀取的是行內樣式文本,用正則替換雖然直觀,但容易誤傷同名字符串;更精準的做法是直接操作具體屬性,例如 div.style.color = 'blue',刪除時把屬性置為空字符串。
第三,能用 class 切換解決的需求,優先用 class 加 CSS 類封裝,這樣樣式集中管理、便於主題化;只有動態數值(如進度寬度、拖動位置)才適合寫進行內樣式。