obj.currentStyle.property、window.getComputedStyle(obj,null).property、obj.style.property 獲取與元素屬性的總結

一 :先看定義:
1 obj.style.property 是一個可讀可寫的,不僅可以獲取屬性的值,而且可以改變屬性的值;
但是需要注意的是此方法只能獲取內嵌在行內元素的屬性值,而不能獲取內聯在 style 標籤 裏面的屬性值,如果內嵌式沒有設置某屬性(比如width),而要通過obj.style.width 來獲取該屬性值,那麼獲取的結果 空字符串
2 obj.currentStyle.property 是IE瀏覽器的孤僻的支持的獲取元素屬性值得方法,可以獲得任何位置設置的元素的屬性值,包括內嵌式,內聯式,外聯式;
3 window.getComputedStyle(obj,null).property 是一個比較大衆的方法,谷歌,火狐,opera,sarifi都支持該方法獲取元素的屬性,其中第二個參數是僞類,如果需要獲取的不是僞類,需要將該值設置爲null;
4 總結 :obj.style.property只能獲取元素的內嵌式樣式屬性值,其他兩個可以獲取內嵌式,內聯式 ,外聯式中設置的屬性值。
二 測試三種方法類型

    var style = window.getComputedStyle (my$("dv"),null);
    console.log("getComputedStyle是"+style);
    // 輸出:getComputedStyle是[object CSSStyleDeclaration]
    var style1 = my$("dv").currentStyle;
    console.log("currentStyle是"+style1);
    // 輸出:getComputedStyle是[object CSSStyleDeclaration]
    var style2 = my$("dv").style;
    console.log("style是"+style2);
    // 輸出:getComputedStyle是[object CSSStyleDeclaration]

由此可知每種方法都是可以獲取某元素的css樣式對象

三,代碼演示

1 設置樣式屬性的情況:

內嵌式:
html代碼

<div id="dv" style="width:50px; height : 40px"></div>

js代碼

var dv = document.getElementById("dv");
console.log(dv.style.width);
console,log(dv.style.height);
console.log(window.getComoutedStyle(dv,null).width;
console.log(dv.currentStyle.width);//Ie瀏覽器

輸出結果:
50px ;
40px
;50px;
50px ;

內聯式或者外聯式

html代碼

style{
    width:50px;
    height:40px;
}
<div id="dv" style="width:50px; height : 40px"></div>

js代碼:

var dv = document.getElementById("dv");
console.log(dv.style.width);
console,log(typeof dv.style.height);
console.log(window.getComoutedStyle(dv,null).width;
console.log(dv.currentStyle.width);//Ie瀏覽器

輸出結果 :
空字符串
string
50px
50px

2 不設置樣式屬性的情況,此時只能
a obj.currentStyle.property、window.getComputedStyle(obj,null).property
b 通過 offsetWidth 和 offsetHeight 注意
來獲取元素的寬高
html 代碼:

    <div id="dv">沒有設置樣式</div>

js代碼:

    var dv = document.getElementById("dv");
    console.log(dv.style.width);
    console,log(typeof dv.style.height);
    console.log(window.getComoutedStyle(dv,null).width;
    console.log(dv.currentStyle.width);//Ie瀏覽器
    console.log(dv.offsetWidth);
    console.log(dv.offsetHeight);

輸出結果:

空字符串
18px
1350px(div元素獨佔一整行瀏覽器的顯示寬度)
1350px(div元素獨佔一整行瀏覽器的顯示寬度)
1350
18

如果將div進行元素轉化:

    <div id="dv" style="position:absolute;">沒有設置樣式</div>

輸出結果:

空字符串
18px
96px
96px
18
96

四 總結:
1 當給元素設置了樣式屬性的時候,obj.style只能獲取內嵌式, obj.currentStyle.property、window.getComputedStyle(obj,null).property;可以獲取任意位置樣式屬性值,僅僅可讀;
offsetWidth offsetHeight 獲取的寬高包括元素的 content(width+height)+ padding+border;而 obj.style, obj.currentStyle.property、window.getComputedStyle(obj,null).property獲取的元素的寬高指的僅僅是 width 和height ,不包括 padding和border
2 如果沒有給元素設置樣式obj.currentStyle.property、window.getComputedStyle(obj,null).property 和offsetWidth offsetHeight都可以獲取由內容撐開的寬高

五 offset系列其他屬性總結:
http://blog.csdn.net/qq_35809245/article/details/53981843

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章