----------------- offset ---------------------
offset家族特點
- 只能取值,不能設(shè)置值
- 獲取的結(jié)果是數(shù)值,不是字符
- 獲取的時候不需要style
網(wǎng)頁可見區(qū)域?qū)挘?document.body.clientWidth;
網(wǎng)頁可見區(qū)域高: document.body.clientHeight;
網(wǎng)頁可見區(qū)域?qū)挘?document.body.offsetWidth (包括邊線的寬);
網(wǎng)頁可見區(qū)域高: document.body.offsetHeight (包括邊線的寬);
網(wǎng)頁正文全文寬: document.body.scrollWidth;
網(wǎng)頁正文全文高: document.body.scrollHeight;
網(wǎng)頁被卷去的高: document.body.scrollTop;
網(wǎng)頁被卷去的左: document.body.scrollLeft;
offsetWidth 和 offsetHeight
- 獲取對象自身的寬度和高度 ,包括內(nèi)容、邊框和內(nèi)邊距,即:offsetWidth = width + border + padding
div{
width: 300px; border-right:2px solid #ccc; padding:10px;
}
注意:和 div.style.width 的區(qū)別,其只能獲取到行內(nèi)的數(shù)值
offsetLeft 和 offsetTop
- 距離第一個有定位的父級盒子左邊和上邊的距離
- 父級盒子必須要有定位,如果沒有,則最終以body為準(zhǔn)!
- offsetLeft 從父親的padding開始算 父親的border不算.即:從子盒子邊框到定位父盒子邊框的距離。
----------------- scroll ---------------------
scroll家族
基本概念
網(wǎng)頁正文全文寬: document.body.scrollWidth;
網(wǎng)頁正文全文高: document.body.scrollHeight;
網(wǎng)頁被卷去的高: document.body.scrollTop;
網(wǎng)頁被卷去的左: document.body.scrollLeft;
在實際開發(fā)中使用比較多的就是scrollTop,如下圖:
處理scroll家族瀏覽器適配問題
-
ie9+ 和 最新瀏覽器
window.pageXOffset; (scrollLeft)
window.pageYOffset; (scrollTop)
-
Firefox瀏覽器 和 其他瀏覽器
document.documentElement.scrollTop;
-
Chrome瀏覽器 和 沒有聲明 DTD <DOCTYPE >
document.body.scrollTop;
兼容寫法
var scrollTop = window.pageYOffset ||
document.documentElement.scrollTop || document.body.scrollTop || 0;
var scrollLeft = window.pageXOffset ||
document.documentElement.scrollLeft || document.body.scrollLeft || 0;
scrollTo(x,y)
把內(nèi)容滾動到指定的坐標(biāo)
-
格式:scrollTo(xpos,ypos)
xpos 必需;要在窗口文檔顯示區(qū)左上角顯示的文檔的 x 坐標(biāo);
ypos 必需;要在窗口文檔顯示區(qū)左上角顯示的文檔的 y 坐標(biāo) 。
網(wǎng)頁大部分都沒有水平滾動條,所以,這個x 不太常用。
----------------- client ---------------------
client家族
1.1 clientWidth和clientHeight
網(wǎng)頁可見區(qū)域?qū)挘?document.body.clientWidth;
網(wǎng)頁可見區(qū)域高: document.body.clientHeight;
1.2 clientLeft和clientTop
-
clientLeft,clientTop
返回的是元素邊框的borderWidth,
如果不指定一個邊框或者不定位改元素,其值就為0
1.3 offset、client和scroll的區(qū)別分析
-
left和top分析:
clientLeft: 左邊邊框的寬度;clientTop: 上邊邊框的寬度
offsetLeft: 當(dāng)前元素距離有定位的父盒子左邊的距離;offsetTop: 當(dāng)前元素距離有定位的父盒子上邊的距離
scrollLeft: 左邊滾動的長度; scrollTop: 上邊滾動的長度;
-
width和height分析
clientWidth/Height: 內(nèi)容 + 內(nèi)邊距
offsetWidth/Height: 內(nèi)容 + 內(nèi)邊距 + 邊框
scrollWidth/Height: 滾動內(nèi)容的寬度和高度