很多交互都需要在運行時改變元素外觀。JavaScript 提供了幾條路徑,它們的效果與副作用並不相同,選錯了容易出現「樣式改了但偽類失效」這類問題。本文逐一實測並對比。
四種方式分別是:
obj.style.cssText 修改內聯樣式;obj.style.具體屬性 修改單條內聯樣式;obj.className 切換樣式表類名;CSS:
.style1{margin:10px auto ;background-color:#9999FF; display:block;color:White; border:1px solid white; padding:10px 25px; font-size:18px; }
.style1:hover{ background-color:#66B3FF; cursor:pointer;}
.style2{margin:10px auto ;background-color:gray; display:block;color:black; border:1px solid white; padding:10px 25px; font-size:18px; }
.style2:hover{ background-color:black; color:White; cursor:pointer}
HTML:
<div> <input id="btnB" type="button" name="btnLogin" value="登錄" class="style1" /> <div id="tool"> <input type="button" value="【obj.style.屬性】更改樣式" onclick="changeStyle1()"/> <input type="button" value="【obj.style.cssText】更改樣式" onclick="changeStyle2()" /> <input type="button" value="【obj.className】更改樣式" onclick="changeStyle3()" /> <input type="button" value="更改外聯css樣式" onclick="changeStyle4()" /> </div> </div>
function changeStyle1() {
var obj = document.getElementById("btnB");
obj.style.backgroundColor = "black";
}
打開浏覽器調試工具會發現 btnB 標簽上多了一個 style 屬性。問題在於樣式的優先級順序是內聯式 > 外聯式,而 :hover 偽類的背景色寫在外聯樣式表中,於是內聯的 background-color 把它壓住了,鼠標移上去感覺不到顏色變化。
function changeStyle2() {
var obj = document.getElementById("btnB");
obj.style.cssText = "background-color:black; display:block;color:White;";
}
效果與問題跟方法一完全相同,本質上都是寫內聯樣式。
function changeStyle3() {
var obj = document.getElementById("btnB");
// obj.className = "style2";
obj.setAttribute("class", "style2");
}
兩種寫法效果一致:直接賦值 className,或用 setAttribute 設置 class。這種方式明顯優於前兩種——樣式定義仍然留在樣式表裡,:hover 等偽類照常生效,樣式與行為分離得也比較乾淨。
先正常引入樣式表:
<link href="css1.css" rel="stylesheet" type="text/css" id="css"/>
function changeStyle4() {
var obj = document.getElementById("css");
obj.setAttribute("href", "css2.css");
}
這是最徹底的一種,改動一行就能讓整頁換一套外觀,非常適合做主題皮膚切換。
只想改一兩個屬性(例如動態計算的寬高、位置),用 obj.style.xxx 最方便;需要切換一整套預設外觀,用切換 className;要做整站換膚,則替換外鏈樣式表最合適。避免用 cssText 大段覆寫,因為它會一併清掉元素上原有的其他內聯樣式。