DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> WEB網站前端 >> 前端技巧
取得元素的最終計算樣式:getComputedStyle 與 currentStyle
編輯:前端技巧     

寫入樣式很簡單,讀出「瀏覽器實際採用哪個值」卻需要專門的 API。這個需求在拖曳、動畫、響應式腳本中很常見——例如你想知道一個元素的實際寬度,而它只寫了 width: 50%。

標準寫法

var view = document.defaultView;
var style = view.getComputedStyle(element, pseudoElt);
var color = style.getPropertyValue('background-color');

兩個參數的含意:

  • element:要查詢的元素。
  • pseudoElt:偽元素字串,例如 ":after"、":before";不需要時傳 null 或省略。

回傳的是一個 CSSStyleDeclaration 物件,用 getPropertyValue() 取值。這裡要注意屬性名必須是「短字串寫法」(kebab-case),例如 background-color,而不是駝峰式。

IE 的舊寫法

var color = element.currentStyle['backgroundColor'];

IE 走 currentStyle,屬性名要駝峰式,且不支援偽元素參數。

兩者的關鍵差異

currentStyle 回傳的是「層疊後但未必是最終計算值」的樣式——像 width: 50% 它就回你 50%。而 getComputedStyle 會回傳用於實際繪製的像素值,這正是多數腳本真正想要的。

相容寫法

function getStyle(elem, prop) {
  if (window.getComputedStyle) {
    return document.defaultView.getComputedStyle(elem, null)
             .getPropertyValue(prop);
  }
  // IE 舊版:需把 kebab-case 轉成 camelCase
  var camel = prop.replace(/-(\w)/g, function (m, c) { return c.toUpperCase(); });
  return elem.currentStyle[camel];
}

補充一點:getComputedStyle 回傳的是即時物件(live object),元素樣式變動後再讀會拿到新值,不需要重新呼叫取得。若只需要單一樣式,也可直接用 style[prop] 的索引寫法,較短但需注意多單字屬性要轉駝峰。

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