# 概念

本质是一个盒子,包括:外边距、边框、内边距、内容
吐槽:为什么我觉得标准才怪。

# web标准盒模型

使用:box-sizing:content-box;(默认)
描述:盒子实际大小为 width + border + padding + content ( content 宽高等于 width)

web标准盒模型;

# IE怪异盒模型

使用:box-sizing:border-box;(默认)
描述:盒子实际大小为 width 与height的值,(content 宽高等于 width - padding - border)
怪异盒模型;

# 示例

ie怪异盒子要小

对比;

<head>
    <style>
        .ie-box {
            box-sizing: border-box;
        }
        .box {
            height: 40px;
            width: 80px;
            padding: 10px;
            border: 5px solid red;
            background: #00AEE8;
            margin: 10px auto;
        }
    </style>
</head>
<body>
<div class="parent">
    <div class="web-box box">
        web-box
    </div>

    <div class="ie-box box">
        ie-box
    </div>
</div>
</body>
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

# JS获取宽高

常用第五种就好了。。

  1. dom.style.width/height 只能取到行内样式的宽和高,style 标签中和 link 外链的样式取不到。
  2. dom.currentStyle.width/height (只有IE兼容)取到的是最终渲染后的宽和高。
  3. window.getComputedStyle(dom).width/height 同(2)但是多浏览器支持,IE9 以上支持。
  4. dom.getBoundingClientRect().width/height 也是得到渲染后的宽和高,大多浏览器支持。IE9 以上支持,除此外还可以取到相对于视窗的上下左右的距离
  5. dom.offsetWidth/offsetHeight 包括高度(宽度)、内边距和边框,不包括外边距。最常用,兼容性最好。
    const $ = function (dom) {
        return document.querySelector(dom)
    }

    console.log( $('.web-box').style.width,  $('.web-box').style.height); // 空值(因为本文实例不是行内样式)
    
    console.log( window.getComputedStyle($('.web-box')).width, 
      window.getComputedStyle($('.web-box')).height);   // 80,40
    
    console.log( $('.web-box').getBoundingClientRect().width, 
      $('.web-box').getBoundingClientRect().height); // 110,70

    console.log( $('.web-box').offsetWidth, $('.web-box').offsetHeight);// 110,70
1
2
3
4
5
6
7
8
9
10
11
12
13
最后更新时间: 6/20/2022, 10:48:50 PM