DIV CSS 佈局教程網

JavaScript 取得樣式的方法整理
編輯:關於JavaScript     

取得元素樣式

element.style 只能取得行內樣式;getComputedStyle 可取得最終樣式;currentStyle 則是舊版 IE 的方案。

var div = document.getElementsByTagName("div")[0];
console.log(div.style.backgroundColor);
console.log(window.getComputedStyle(div, null).backgroundColor);

相容性寫法

function getStyle(obj, attr){
  if(obj.currentStyle){
    return obj.currentStyle[attr];
  }
  return window.getComputedStyle(obj, false)[attr];
}

getPropertyValue

若屬性名稱含連字號,可使用 getPropertyValue:

window.getComputedStyle(obj, null).getPropertyValue('background-color');

在 Firefox 3.6 存取 iframe 內樣式時,可能需要 document.defaultView.getComputedStyle。

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