<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> html, body { height: 100%; } body { border: 1px solid red; } </style></head><body><div style="height:1000px;"></div></body><script> let clientWidth = document.body.clientWidth; let clientHeight = document.body.clientHeight; console.log('1. 視口寬:', clientWidth, ' 視口高:', clientHeight); let offWidth = document.body.offsetWidth; let offHeight = document.body.offsetHeight; console.log('2. offsetWidth: ', offWidth, 'offsetHeight: ', offHeight); let scrollWidth = document.body.scrollWidth; let scrollHeight = document.body.scrollHeight; console.log('3. scrollWidth: ', scrollWidth, ' scrollHeight: ', scrollHeight);</script></html>
1、document.body的 clientWidth, clientHeight**(視口大小)**
當給body,html設定height:100%後,body的寬預設100%的情況下,可以使用
document.body.clientWidth ,document.body.clientHeight 取到的值,可以視為視口大小,且chrome,ie,firefox表現一致(javascript進階程式設計第三版8.1.4)。
document.body.clientWidth = body的width+padding*2
當給body設定的寬度不是100%,比如是400px的時候,document.body.clientWidth ,取到的是body的寬。
2、document.body的 offsetWidth, offsetHeight。可以看成,offsetWidth=clientWidth+border = width+pading*2+border*2; offsetHeight同理。
3、document.body的 scrollWidth,scrollHeight。相當於body的 (內容寬高)。
如body中有個div,高度為1000px。那麼document.body.scrollHeight = 1000。
如果div有margin,padding,border,那麼document.body.scrollHeight = div的高度+margin*2+padding*2+border*2 + body的上padding;