用 JavaScript 改樣式時,屬性名稱不能照抄 CSS。這條轉換規則非常簡單,但有一個著名的例外,幾乎每個人都要查一次。
obj.style.margin;
obj.style.width;
obj.style.left;
obj.style.position;
obj.style.marginTop; // margin-top
obj.style.borderLeftWidth; // border-left-width
obj.style.zIndex; // z-index
obj.style.fontFamily; // font-family
原因是 JS 的減號是運算子,style.margin-top 會被解析成「style.margin 減 top」而報錯,所以必須換成合法的識別字。這套規則也通用于 getComputedStyle 讀取屬性時。
float 是 JavaScript 的保留字,因此 obj.style.float = 'left' 是無效語法。正確寫法要分瀏覽器:
// IE
obj.style.styleFloat = 'left';
// Firefox、其他 Mozilla 核心
obj.style.cssFloat = 'left';
原範例的示範把兩者寫成條件判斷,值得照抄:
<div onclick="
if (this.style.cssFloat) { this.style.cssFloat = 'left'; }
else { this.style.styleFloat = 'left'; }
">測試</div>
注意原範例中 alert(this.style.float) 無論怎麼設定都會拿到 undefined,因為那個屬性根本不存在——這也說明為什麼「讀不到值」不一定是邏輯錯,可能只是屬性名寫錯了。
background-color → backgroundColorpadding-left → paddingLefttext-align → textAlignline-height → lineHeight-webkit-transform → 在 JS 中通常寫 WebkitTransform(大寫開頭)廠商前綴屬性在 JS 中的命名規則(首字母大寫)容易搞錯,現在更好的方式是直接用 setProperty,它吃 CSS 原始寫法:
el.style.setProperty("background-color", "red");
el.style.removeProperty("float");
而 float 在現代排版中幾乎已被 Flexbox 與 Grid 取代;若只是想讓元素靠左,用 justify-content、text-align 或 margin-inline 更合適,也就不必再跟 cssFloat 這個歷史包袱纏鬥。