還是自己遇到的一個坑的總結吧!與其說是坑不如說自己學藝不精,讓我先哭一會!!
需求
簡單就是獲取一個css的height
(好吧 就是一個這么簡單的需求)
實踐
好吧 長時間的JQ 我已經對原生無能了 讓我默哀3秒!!!
document.querySelector('.className').style.height;
這個果然不生效 好吧 看來我真的倒退不少!讓我再哭一會!!(哭你妹 快去總結)
在學習中發現 其實js原生獲取css的方法很多,上面寫的就是其中一種,只不過情景不對啊!
getComputedStyle
- 說明 一個可以獲取當前元素所有最終使用的CSS屬性值。返回的是一個CSS樣式聲明對象([object CSSStyleDeclaration])
簡單來說 讀出你八輩祖宗的一個方法。
- 語法 window.getComputedStyle(dom, '偽元素')
看到偽元素、我就懵逼了 我只知道偽類啊 這有神馬區別?
偽元素 其實就是 ::before :: after :: first-line ::first-letter ::content 等等
偽類 :hover :link :first-child :active 等等
- 用法
var oImg = document.getElementById('photo');
window.getComputedStyle(oImg, null).height;
dom.style
-
說明 獲取元素style屬性中的CSS樣式, 簡單說就是 能讀能寫 只能讀你的外表
-
語法 dom.style.樣式名稱
-
用法
var oImg = document.getElementById('photo');
oImg.style.height; // 只能獲取css 樣式表的
currentStyle
-
說明 返回的是元素當前應用的最終CSS屬性值(包括外鏈CSS文件,頁面中嵌入的
<style>
屬性等)與getComputedStyle
那個讀你八輩祖宗的很像,但是不能獲取偽元素。且他們獲取的屬性也有很大差異。 -
語法 element.currentStyle.樣式
-
用法
var oImg = document.getElementById('photo');
oImg.currentStyle.height; // 只能獲取css 樣式表的
getPropertyValue和getAttribute
-
說明 可以獲取CSS樣式申明對象上的屬性值(直接屬性名稱),
getPropertyValue可以不用駝峰,直接用其屬性名
getAttribute主要是為了兼容IE獲取屬性值,需要駝峰的寫法 -
語法
getPropertyValue("background-color")
getAttribute("backgroundColor")
-
用法
var oImg = document.getElementById('photo');
var oStyle = oImg.currentStyle? oImg.currentStyle : window.getComputedStyle(oImg, null);
oStyle.getPropertyValue("background-color")
oStyle.getAttribute("backgroundColor")
總結
如果我想獲取某個屬性值可以 比如高度 ?
(dom.currentStyle? dom.currentStyle : window.getComputedStyle(dom, null)).height;
如果是復合的某個屬性獲取?
(oImg.currentStyle? oImg.currentStyle : window.getComputedStyle(oImg, null)).getPropertyValue("background-color")
如果我想給這個屬性重新設置這個高度?
可以先用上面方法取到,然后用
dom.style.height = XX + 'px';
如果是復合的屬性值,請注意是駝峰的寫法!
其實在看了這些以后,我用了上面的這個方法我依然沒有獲取到這個圖片的高度?為什么啊 ?
因為圖片存在一個加載的問題,你剛進來獲取當然無法獲取到? 其實可以用onload事件來解決,具體還有其他更多的方法。