代码
<!DOCTYPE html>
<html lang="zh_CN">
<style>
.outer{
width: 100px;height: 100px;
background: yellow;
padding:10px;
margin:15px;
border:5px solid black;
overflow: auto;
/* box-sizing: border-box; */
}
.inner{
height: 20px;
border-bottom: 1px solid silver;
}
</style>
<body>
<div class="outer" id="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
</body>
<script>
let outer = document.querySelector('#outer');
console.log('clientWidth:', outer.clientWidth, 'width: 100px + padding: 10px * 2 - 滚动条宽度');
console.log('offsetWidth:', outer.offsetWidth, 'width: 100px + padding: 10px * 2 + border: 5px * 2');
console.log('scrollWidth:', outer.scrollWidth, '横向没有溢出时等于clientWidth');
console.log('clientHeight:', outer.clientHeight, 'height: 100px + padding: 10px * 2'); // 如果有横向滚动条就要减去滚动条宽度了,比如overflow设置为scroll
console.log('offsetHeight:', outer.offsetHeight, 'height: 100px + padding: 10px * 2 + border: 5px * 2');
console.log('scrollHeight:', outer.scrollHeight, 'height: 20px * 10 + padding: 10px * 2 + border-bottom: 1px * 10');
// border-box
// console.log('clientWidth:', outer.clientWidth, 'width: 100px - border:5px * 2 - 滚动条宽度');
// console.log('offsetWidth:', outer.offsetWidth, 'width: 100px');
// console.log('scrollWidth:', outer.scrollWidth, '横向没有溢出时等于clientWidth');
// console.log('clientHeight:', outer.clientHeight, 'height: 100px - border: 5px * 2'); // 如果有横向滚动条就要减去滚动条宽度了,比如overflow设置为scroll
// console.log('offsetHeight:', outer.offsetHeight, 'height: 100px');
// console.log('scrollHeight:', outer.scrollHeight, '(height: 20px + border-bottom: 1px) * 10 + padding: 10px * 2');
</script>
</html>
结果
width: 100px; height: 100px; border: 5px; padding: 10px; margin: 15px;
box-sizing: content-box; (padding/border在给定width之外绘制)
box-sizing: border-box; (padding/border在width内绘制)
总结
- clientHeight / clientWidth 计算元素内可用区的高度、宽度。(图中黄色部分,包含padding,不计算内容超出元素部分)(滚动条宽度不同环境不一样)
- offsetHeight / offsetWidth 计算元素整体占用的高度、宽度。(不包括margin部分)
- scrollHeight / scrollWidth 当内容溢出时,计算元素内子节点总高度、宽度,否则等于clientHeight / clientWidth。
- 附:window.innerHeight / innerWidth 计算浏览器可视区的高度、宽度
若有错误/补充,敬请指出。