1. 程式人生 > >JS獲取元素樣式之style、currentStyle、getComputedStyle

JS獲取元素樣式之style、currentStyle、getComputedStyle

在js中獲取元素的樣式屬性大多都是用ele.style.attr這種方式,但是這種方式是有侷限性的,該方法只能獲取到行內樣式,獲取不了外部樣式。
如果要想獲取元素的外部樣式,可以選用currentStyle屬性和getComputedStyle屬性,但這兩個屬性不能設定樣式,只能獲取樣式,而且這兩個屬性有其相容性,具體來說:
currentStyle屬性
用法:ele.currentStyle["attr"]ele.currentStyle.attr
特點:該屬性只相容IE,不相容火狐和谷歌
getComputedStyle屬性
用法:window.getComputedStyle(ele,null)[attr]

window.getComputedStyle(ele,null).attr
(兩個引數,元素和偽類。第二個引數不是必須的,當不查詢偽類元素的時候可以忽略或者傳入 null)
特點:該屬性是相容火狐谷歌,不相容IE8及以下(IE9及以上版本可相容)
基於此,我們可以寫一個相容性的方法來獲取元素樣式:

function getCss(element, attr) {
   if (window.getComputedStyle) {
    return attr?window.getComputedStyle(element, null)[attr]:window.getComputedStyle(element, null
); } return attr?element.currentStyle[attr]:element.currentStyle; } var oBox = document.getElementById("box"); getCss(oBox,"font-size");

style,currentStyle和getComputedStyle的區別

操作 特點
style 1.各大瀏覽器都相容,能設定樣式和獲取樣式;
2.獲取不了外部樣式,如果寫了行內沒有的樣式,返回的是空值
currentStyle 1.該屬性只相容IE,不相容火狐和谷歌;
2.該屬性不能設定樣式,只能獲取樣式
getComputedStyle 1.該屬性是相容火狐谷歌,不相容IE8及以下(IE9及以上版本可相容);
2.該屬性不能設定樣式,只能獲取樣式