依情境動態改變元素外觀是前端的基本功。實作上主要有兩條路:直接操作 style,或切換 className。下面用一個範例示範兩者,並提醒幾個容易出錯的細節。
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.softwhy.com/" />
<head>
<title>動態設置div的樣式</title>
<style type="text/css">
div{
width:50px;
height:50px;
background:red;
margin-top:10px;
}
.bg{
background-color:blue;
}
</style>
<script type="text/javascript">
window.onload=function(){
var firstDiv=document.getElementById("firstDiv");
var secondDiv=document.getElementById("secondDiv");
var first=document.getElementById("first");
var second=document.getElementById("second");
first.onclick=function(){
firstDiv.style.backgroundColor="green";
}
second.onclick=function(){
secondDiv.className="bg";
}
}
</script>
</head>
<body>
<div id="firstDiv"></div>
<div id="secondDiv"></div>
<input type="button" value="使用style方式" id="first" />
<input type="button" value="使用className方式" id="second" />
</body>
</html>
兩顆按鈕分別用兩種方式改了背景色。
1. 用 style 時,含連字號的屬性要改寫成駝峰式。CSS 裡的 background-color 在 JS 中必須寫成 backgroundColor(第二個單字首字母大寫),直接寫 'background-color' 是無效的。
2. 用 className 時,值就是 class 名稱本身,前面不能加點。寫成 className = ".bg" 不會生效。
兩種方式如何取捨?若只是改一兩個屬性、且該狀態不會重複使用,用 style 直接;若是一整套視覺狀態(例如「選中」「禁用」「展開」),定義成 class 再切換會乾淨得多,樣式與行為分離,也方便除錯。
當需要按鈕一顆顆對應不同屬性時,可以像下面這樣把屬性名與值放進陣列、用索引對應,並在最後一顆按鈕上做還原:
<script type="text/javascript">
var oBox = document.getElementById('box');
var oDiv = document.getElementById('div1');
var aInput = document.getElementsByTagName('input');
var aAttr = ['width', 'height', 'backgroundColor', 'display', 'display'];
var aValue = ['200px', '200px', 'red', 'none', 'block'];
for(var len=aInput.length,i=0;i<len;i++){
aInput[i].index = i; //索引
aInput[i].onclick = function(){
//重置按鈕,cssText清空DIV屬性
if(this.index == aInput.length - 1) oDiv.style.cssText = "";
//設置DIV屬性
property(oDiv, aAttr[this.index], aValue[this.index]);
};
}
//控制DIV屬性
function property(obj, attr, value){
obj.style[attr] = value;
}
</script>
這裡有兩個值得學的技巧:把索引掛在元素上(aInput[i].index = i)可以避開迴圈中 function 作用域的取值問題;而 style.cssText = "" 是清空所有行內樣式最快速的方式,比逐一刪除屬性方便。