W3C盒模型


本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/09/17/W3C%E7%9B%92%E6%A8%A1%E5%9E%8B/

摘要

本文主要讲述了:

  1. W3C 盒模型
  2. offsetWidth
  3. offsetHeight
  4. clientWidth
  5. clientHeight
  6. scrollWidth
  7. scrollHeight
  8. 测试用例

正文

W3C 盒模型

  • width = content-box-width + vertical-scroll-bar-width
  • height = content-box-height + horizontal-scroll-bar-height

注:

  • widthheight为内容区理论可用的最大宽高,但是一旦出现滚动条,就会塌缩成content-box-widthcontent-box-height
  • 垂直滚动条悬浮在padding-right右侧的最上层
  • 水平滚动条悬浮在padding-bottom下侧的最上层

offsetWidth

修约为整数

offsetWidth = border-left-width + padding-left + width + padding-right + border-right-width

offsetHeight

修约为整数

offsetHeight = border-top-width + padding-top + height + padding-bottom + border-right-width

clientWidth

修约为整数

clientWidth = padding-left + content-box-width + padding-right

clientHeight

修约为整数

clientHeight = padding-top + content-box-height + padding-bottom

scrollWidth

修约为整数

  • scrollWidth = padding-left + ::before + content-width + ::after + padding-right
  • scrollWidth >= clientWidth

注:

  • 对于横向排列的文字而言:content-widthcontent-box-width

scrollHeight

修约为整数

  • scrollHeight = padding-top + ::before + content-height + ::after + padding-bottom
  • scrollHeight >= clientHeight

注:

  • 对于横向排列的文字而言:content-height为按照content-box-width的宽度排列,完整容纳所需的高度

测试用例

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="foo">
一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十
</div>
<style>
#foo {
width: 100px;
height: 100px;
border: 100px solid #000;
padding: 100px;
margin: 100px;
overflow: scroll;
}
#foo::before {
content: '';
display: block;
width: 100px;
height: 100px;
background-color: #f00;
}
#foo::after {
content: '';
display: block;
width: 100px;
height: 100px;
background-color: #f00;
}
</style>
<script>
const foo = document.getElementById('foo');

window.addEventListener('click', function () {
// 输出:500
console.log(foo.offsetWidth);
// 输出:500
console.log(foo.offsetHeight);
// 输出:283
console.log(foo.clientWidth);
// 输出:283
console.log(foo.clientHeight);
// IE:283
// Firefox:283
// Chrome:300
console.log(foo.scrollWidth);
// IE:448
// Firefox:544
// Chrome:568
console.log(foo.scrollHeight);
// IE:83px
// Firefox:100px
// Chrome:83px
console.log(getComputedStyle(foo).width);
// IE:83px
// Firefox:100px
// Chrome:83px
console.log(getComputedStyle(foo).height);
});
</script>
</body>
</html>

参考资料

本文作者: jsweibo

本文链接: https://jsweibo.github.io/2019/09/17/W3C%E7%9B%92%E6%A8%A1%E5%9E%8B/


本文对你有帮助?请支持我


支付宝
微信