<!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;