js 獲取頁面/元素的寬、高、距離

Document對象是每個DOM樹的根,但是它並不代表樹中的一個HTML元素,
document.documentElement屬性引用了作爲文檔根元素的html標記,

整個文檔的寬度:document.documentElement.scrollWidth
整個文檔的高度:document.documentElement.scrollHeight
整個文檔的可見寬度:document.documentElement.clientWidth (不包含邊框的寬)
整個文檔的可見高度:document.documentElement.clientHeight (不包含邊框的寬)
整個文檔的可見寬度:document.documentElement.offsetWidth (包括邊線的寬)
整個文檔的可見高度:document.documentElement.offsetHeight (包括邊線的寬)

document.body屬性引用了body標記
body正文全文寬:document.body.scrollWidth
body正文全文高:document.body.scrollHeight
body可見區域寬:document.body.clientWidth (不包括邊線的寬) width+左右padding
body可見區域高:document.body.clientHeight (不包括邊線的高) height + 上下padding
body可見區域寬:document.body.offsetWidth (包括邊線的寬)
body可見區域高:document.body.offsetHeight (包括邊線的高)

var cWidth = document.body.clientWidth || document.documentElement.clientWidth;//頁面可視區域寬度
var iWidth = window.innerWidth;//瀏覽器窗口大小
console.log(iWidth - cWidth);//打印滾動條寬度

在不同的瀏覽器中,有些能識別document.body.scrollTop,有些能識別document.documentElement.scrollTop
網頁被捲去的高:document.body.scrollTop || document.documentElement.scrollTop
網頁被捲去的左:document.body.scrollLeft || document.documentElement.scrollLeft

body和documentElement的區別
document.body.scrollHeight == document.body.offsetHeight == document.body.clientHeight
document.documentElement.scrollHeight == document.documentElement.offsetHeight

document.body.scrollHeight ≠ document.documentElement.scrollHeight
document.body.offsetHeight ≠ document.documentElement.offsetHeight
document.body.clientHeight ≠ document.documentElement.clientHeight

網頁正文部分上:window.screenTop
網頁正文部分左:window.screenLeft
屏幕分辨率的高:window.screen.height
屏幕分辨率的寬:window.screen.width
屏幕可用工作區高度:window.screen.availHeight
屏幕可用工作區寬度:window.screen.availWidth

獲取可視區窗口寬度:window.innerWidth
獲取可視區窗口高度:window.innerHeight

clientWidth = 元素width + 元素左右padding
clientHeight = 元素height + 元素上下padding
clientLeft 屬性返回元素左邊框的寬度(border)。此屬性不包括元素的左margin或左padding 。此屬性是隻讀的。
提示:您還可以使用style.borderLeftWidth屬性返回元素左邊框的寬度。
clientTop屬性返回元素頂部邊框的寬度。此屬性不包括元素的頂部填充或上邊距。此屬性是隻讀的。
提示:您還可以使用style.borderTopWidth屬性返回元素頂部邊框的寬度。

offsetWidth = 元素width + 元素左右padding + 元素左右boder = clientWidth + 元素左右boder
offsetHeight = 元素height + 元素上下padding + 元素上下boder = clientHeight + 元素上下boder
offsetLeft = 當前元素 marginLeft + 最近的已定位父級(offsetParent) paddingLeft
offsetTop = 當前元素 marginTop + 最近的已定位父級(offsetParent) paddingTop
如果父級都沒有定位,offsetLeft,offsetTop 是當前元素 分別到 body 頂部 和 左邊 的距離。

 

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