每一個HTML元素都有以下屬性
offsetWidth | offsetHeight | offsetLeft | offsetTop |
clientWidth | clientHeight | ||
scrollWidth | scrollHeight | scrollLeft | scrollTop |
1. 偏移量(offsetHeight offsetWidth offsetLeft offsetTop)
offsetHeight/offsetWidth: 表述元素的外尺寸:元素內容+內邊距+邊框(不包括外邊距)
offsetLeft/offsetTop: 表示該元素的左上角(邊框外邊緣)與已定位的父容器(offsetParent對象)左上角的距離。
offsetParent元素是指元素最近的定位(relative,absolute)祖先元素,可遞歸上溯。
/** * 獲取元素在頁面中的坐標(x, y) * @param {Object} e */ function getElementPosition(e) { var x = 0, y = 0; while(e != null) { x += e.offsetLeft; y += e.offsetTop; e = e.offsetParent; } return { x: x, y: y }; }
2. 客戶區大小(clientWidth clientHeight)
clientWidth/clientHeight: 用於描述元素的內尺寸:元素內容+兩邊內邊距
innerWidth/innerHeight
常用於獲取視口的高寬
/** * 獲取視口的大小 * 用法: * var viewport = getViewportSize(); * viewport.width/viewport.height * @param {Object} w */ function getViewportSize(w) { var w = w || window; if(w.innerHeight != null) { return { w: w.innerWidth, h: w.innerHeight }; } var d = w.document; if(document.compatMode == 'CSS1Compat') { //標准模式 return { width: d.documentElement.clientWidth, height: d.documentElement.clientHeight }; } return { w: d.body.clientWidth, h: d.body.clientHeight }; }
3. 滾動大小(scrollHeight scrollWidth scrollLeft scrollTop)
scrollHeight/scrollWidth: 元素內容的總高度或寬度
scrollLeft/scrollTop:是指元素滾動條位置,它們是可寫的(被隱藏的內容區域左側/上方的像素)
瀏覽器窗口的滾動條位置:window對象的pageXoffset和pageYoffset, IE 8及更早版本可以通過scrollLeft和scrollTop屬性獲得滾動條位置
/** * 獲取滾動長度 * 滾動條向下滾動被隱藏的頁面長度 * 通用的scrollLeft和scrollTop * @param {Object} w */ function getScrollOffset(w) { var w = w || window; //Firefox if(w.pageXOffset != null) { return { x: w.pageXOffset, y: w.pageYOffset }; } var d = w.document; if(document.compatMode == 'CSS1Compat') { //標准模式 return { x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop }; } // return { x: d.body.scrollLeft, y: d.body.scrollTop }; }
小結:
注意:這些屬性都是很多是只讀的,每次訪問它們都需要重新計算
整個頁面的高度:document.documentElement.scrollHeight
內容區上面被隱藏的頁面高度: window.pageYOffset/document.documentElement.scrollTop
element.offsetHeight = element.clientHeight + borderLeft-width*2
參考:http://www.cnblogs.com/dolphinX/archive/2012/11/19/2777756.html
HTML DOCUMENT窗口的尺寸和位置