用 JavaScript 改樣式看似簡單,但大小寫、要不要加 style、跨瀏覽器的屬性名稱差異,都是常見的踩雷點。以下把局部改Style與全域換表的做法分開整理。
改變 className、改變 cssText、直接設定單一屬性,各有不同的注意事項。
大小寫要留意。JavaScript 對大小寫敏感,className 的 N 不能寫成 n,cssText 的 T 也不能寫成 t,否則完全不生效。
改 className 時不要加 style。先把類別宣告在樣式表裡,呼叫時直接寫:
document.getElementById('obj').className = "newClass";
寫成 document.getElementById('obj').style.className = "..." 是錯的。
改 cssText 時反而必須加 style:
document.getElementById('obj').style.cssText = "color:#fff; background:#000;";
改單一屬性就是逐項指定,記得寫到具體的樣式名稱:
document.getElementById('obj').style.backgroundColor = "#003366";
想做「換版型」這種效果,做法是給 link 標籤一個 id,然後改它的 href:
<link rel="stylesheet" type="text/css" id="css" href="firefox.css" />
<span onclick="javascript:document.getElementById('css').href = 'ie.css'">
點我改變樣式
</span>
CSS 屬性轉成 JavaScript 時有些要注意:連字號風格要改寫成駝峰式,例如 background-color 變成 backgroundColor。也有真正分歧的例子,float 在 IE 是 styleFloat,在 Firefox 是 cssFloat,這類差異只能靠平時累積。
第一種,外部連結:
<head>
<title>文檔標題</title>
<link rel="stylesheet" href="demo.css" type="text/css" />
</head>
在 XML 中則於宣告區加入 <?xml-stylesheet type="text/css" href="demo.css" ?>。
第二種,內部樣式區塊:
<html>
<head>
<title>文檔標題</title>
<style type="text/css">
<!--
body { font: 10pt "Arial" }
h1 { font: 15pt/17pt "Arial"; font-weight: bold; color: maroon }
h2 { font: 13pt/15pt "Arial"; font-weight: bold; color: blue }
p { font: 10pt/12pt "Arial"; color: black }
-->
</style>
</head>
<body></body>
</html>
把 style 的 type 設為 text/css,可讓不支援的瀏覽器直接忽略整段樣式。
第三種,行內樣式:
<p style="margin-left: 0.5in; margin-right: 0.5in">這一行被加上了左右內距</p>