一,獲取元素的css大小
1.通過style內聯獲取元素的大小
var box = document.getElementById('box'); // 獲得元素;
box.style.width; // 200px;
box.style.height;
2.通過計算獲取元素的大小
var style = window.getComputedStyle ? window.getComputedStyle(box,null) : null || box.currentStyle;
style.width;
3.通過CSSStyleSheet對象中的cssRules(或rules)屬性獲取元素的大小;
var rule = (sheet.cssRules || sheet.rules)[0]; // 獲取第一條規則;
rule.style.width;
二 獲取元素實際大小
1.clientWidth和clientHeight
返回了元素大小,但沒有單位,默認單位是px;
PS:對於元素的實際大小,clientWidth和clientHeight理解如下:
1.元素增加邊框,無變化,200;
2.元素增加外邊框,無變化,200;
3.增加滾動條,最終值=原本大小-滾動條大小;184;
4.增加內邊距,最終值=原本大小+內邊距大小;220;
PS:如果沒有設置任何CSS的width和height,那么非IE會算上滾動條和內邊距的計算后的大小;而IE則返回0;
2.scrollWidth和scrollHeight
這組屬性可以獲取沒有滾動條的情況下,元素內容的總高度;
box.scrollWidth;
// PS:返回了元素大小,默認單位是px;如果沒有設置任何CSS的width和height,它會得到計算后的寬度和高度;
3.offsetWidth和offsetHeight
這組屬性可以返回元素實際大小,包含邊框/內邊距和滾動條;
box.offsetWidth; 200
PS:返回了元素大小,默認單位是px;如果沒有設置任何CSS的width和height,它會得到計算后的寬度和高度;
PS:對於元素的實際大小,理解如下:
1.增加邊框,最終值=原本大小+邊框大小;220;
2.增加內邊距,最終值=原本大小+內邊距大小;220;
3.增加外邊據,無變化;
4.增加滾動條,無變化,不會減小;
PS:對於元素大小的獲取,一般是塊級(block)元素並且已設置了CSS大小的元素較為方便;
1 var flag = true; 2 3 if (flag) { 4 var script = document.createElement('script'); 5 script.type = "text/javascript/"; 6 script.text = "alert('test')"; 7 document.getElementByTagName("head")[0].appendChild(script);
}
