DIV CSS 佈局教程網

用 JavaScript 操作 CSS 時該注意的幾件事
編輯:關於JavaScript     

透過 element.style 改樣式時,有幾個和 CSS 原始寫法不一致的地方,很容易出錯。

一、連字號變成駝峰式

style 物件上的屬性名稱與 CSS 屬性幾乎一一對應,但凡含連字號的都改成駝峰寫法:

font-size   →  fontSize
margin-top  →  marginTop
background-color → backgroundColor

二、float 是保留字

float 在 JavaScript 中是保留關鍵字,所以不能用 style.float。標準寫法是 style.cssFloat,而舊版 IE 用的是 style.styleFloat:

if (typeof elem.style.cssFloat !== 'undefined') {
  elem.style.cssFloat = 'left';
} else {
  elem.style.styleFloat = 'left';
}

三、讀取 computed style

寫入用 style,但讀取「實際生效的樣式」必須用 computed style——因為 elem.style 只包含行內樣式,讀不到樣式表裡的規則。W3C 標準環境:

var heading = document.getElementById("heading");
var computedStyle = document.defaultView.getComputedStyle(heading, null);
var computedFontFamily = computedStyle.fontFamily; // sans-serif

IE 用的是 currentStyle:

var computedFontFamily = heading.currentStyle.fontFamily;

合成一個跨瀏覽器函式:

function retrieveComputedStyle(element, styleProperty) {
  var computedStyle = null;
  if (typeof element.currentStyle != "undefined") {
    computedStyle = element.currentStyle;
  } else {
    computedStyle = document.defaultView.getComputedStyle(element, null);
  }
  return computedStyle[styleProperty];
}

要注意兩者的差異不只是名稱:getComputedStyle 回傳的是經過層級與計算後的最終值(例如 width 會是像素值),而 currentStyle 有時回傳的是尚未計算的宣告值。依賴這個差異的程式碼在跨瀏覽器時容易出錯。

四、屬性名稱對照

常見對應如下:

  • background-attachment → backgroundAttachment
  • border-bottom-width → borderBottomWidth
  • font-family / font-size → fontFamily / fontSize
  • letter-spacing / line-height → letterSpacing / lineHeight
  • list-style-type → listStyleType
  • page-break-after → pageBreakAfter
  • text-align / text-indent → textAlign / textIndent
  • vertical-align → verticalAlign
  • z-index → zIndex

五、各瀏覽器的寫入語法

Internet Explorer:document.all.div_id.style.JS_property = "value";

較舊的 Netscape 4.x:document.div_id.JS_property = "value";

Netscape 6+、Opera 與其他 Mozilla 系:document.getElementById(div_id).style.JS_property = "value";

最後一個實務建議:能用 class 切換解決的就不要逐屬性寫 JS。把 elem.style.cssText = '...' 換成 elem.className = 'active',樣式與行為分離之後,維護成本會低很多,也避開了上面所有名稱轉換的坑。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved