js操作相關知識(一)

1、getAttribute、setAttribute

  1. getAttribute()方法是一個函數。它只有一個參數 —— 你打算查詢的屬性的名字:
    object.getAttribute(attribute)
    不過,getAttribute()方法不能通過document對象調用,這與我們此前介紹過的其他方法不同。我們只能通過一個元素節點對象調用它。
  2. setAttribute()方法需要我們向它傳遞兩個參數:
    obiect.setAttribute(attribute,value)

來源:https://www.cnblogs.com/sunky/articles/2322734.html

2、currentStyle、getComputedStyle

原作者 : by zhangxinxu from http://www.zhangxinxu.com
原文 : http://www.zhangxinxu.com/wordpress/?p=2378
引用自 : https://blog.csdn.net/sunny327/article/details/46359953

2.1 getComputedStyle是?

getComputedStyle是一個可以獲取當前元素所有最終使用的CSS屬性值。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration]),只讀

    getComputedStyle() gives the final used values of all the CSS properties of an element.

語法如下:

var style = window.getComputedStyle("元素", "僞類");

// 例如:

var dom = document.getElementById("test"),
    style = window.getComputedStyle(dom , ":after");

就兩個參數,大家都懂中文的,沒什麼好說的。只是額外提示下:Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) 之前,第二個參數“僞類”是必需的(如果不是僞類,設置爲null),不過現在嘛,不是必需參數了。

2.2 getComputedStyle與style的區別

我們使用element.style也可以獲取元素的CSS樣式聲明對象,但是其與getComputedStyle方法還有有一些差異的。

  1. 只讀與可寫
    正如上面提到的getComputedStyle方法是隻讀的,只能獲取樣式,不能設置;而element.style能讀能寫,能屈能伸。
  2. 獲取的對象範圍
    getComputedStyle方法獲取的是最終應用在元素上的所有CSS屬性對象(即使沒有CSS代碼,也會把默認的祖宗八代都顯示出來);而element.style只能獲取元素style屬性中的CSS樣式。因此對於一個光禿禿的元素 <p>getComputedStyle方法返回對象中length屬性值(如果有)就是190+(據我測試FF:192, IE9:195, Chrome:253, 不同環境結果可能有差異), 而element.style就是0。

2.3 currentStyle、getComputedStyle

currentStyle是IE瀏覽器自娛自樂的一個屬性,其與element.style可以說是近親,至少在使用形式上類似,element.currentStyle,差別在於element.currentStyle返回的是元素當前應用的最終CSS屬性值(包括外鏈CSS文件,頁面中嵌入的

因此,從作用上將,getComputedStyle方法與currentStyle屬性走的很近,形式上則style與currentStyle走的近。不過,currentStyle屬性貌似不支持僞類樣式獲取,這是與getComputedStyle方法的差異,也是jQuerycss()方法無法體現的一點。

//zxx: 如果你只知jQuery css()方法,你是不會知道僞類樣式也是可以獲取的,雖然部分瀏覽器不支持。

例如,我們要獲取一個元素的高度,可以類似下面的代碼:

var s=((element.currentStyle? element.currentStyle : window.getComputedStyle(element, null)));
console.log(a.height);

您可以狠狠地點擊這裏:使用getComputedStyle和currentStyle 獲取元素高度demo
結果FireFox下顯示24px(經過計算了), 而IE瀏覽器下則是CSS中的2em屬性值:
在這裏插入圖片描述在這裏插入圖片描述
仔細對比查看,我們可以看到不少差異,例如浮動屬性,FireFox瀏覽器下是這個(cssFloat):
在這裏插入圖片描述
IE7瀏覽器下則是styleFloat :
在這裏插入圖片描述
而IE9瀏覽器下則是cssFloat和styleFloat都有。
等其他N多差異。

2.4 getPropertyValue和getAttribute

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