盒模型以及相关dom API

盒模型:

代码:

<div class="content-box">Content box</div>
<br />
<div class="border-box">Border box</div>
div {
  width: 160px;
  height: 80px;
  padding: 20px;
  border: 8px solid red;
  background: yellow;
}

.content-box {
  box-sizing: content-box;
  /* Total width: 160px + (2 * 20px) + (2 * 8px) = 216px
     Total height: 80px + (2 * 20px) + (2 * 8px) = 136px
     Content box width: 160px
     Content box height: 80px */
}

.border-box {
  box-sizing: border-box;
  /* Total width: 160px
     Total height: 80px
     Content box width: 160px - (2 * 20px) - (2 * 8px) = 104px
     Content box height: 80px - (2 * 20px) - (2 * 8px) = 24px */
}

标准盒模型(默认模型)

box-sizing: content-box;

内容宽度: 160
内容高度: 80

怪异盒模型

box-sizing: border-box;

总共宽度: 104+20+20+8+8 = 160

总共高度:  8+20+24+20+8 = 80

内容宽度: 160px - (2 * 20px) - (2 * 8px) = 104px
内容高度:  80px - (2 * 20px) - (2 * 8px) = 24px

宽度属性以及API(高度类似):

(1)clientWidth

  • 包含内边距,不包括边框、外边距和垂直滚动条宽度
  • 值是整数

   按上面的例子(值是不带单位的):

   content-box: 200

   border-box: 144

(2)offsetWidth

  • 包含边框、内边距和垂直滚动条宽度
  • 如果元素隐藏或者父节点style.display的值设置为none,返回0
  • 值是整数

   按上面的例子(值是不带单位的):

   content-box: 216

   border-box: 160

(3)scrollWidth

  • 包括内边距,不包括边框、外边距和垂直滚动条宽度
  • 包含伪元素::before和::after
  • 没有水平滚动条,等同于clientWidth
  • 值是整数

   按上面的例子(值是不带单位的,水平没有滚动条):

   content-box: 200

   border-box: 144

(4)getBoundingClientRect

  • 值可以为小数,需要比较精确可以用这个api

 按上面的例子(值是不带单位的):

 宽度 = 内容宽度+ 内边距 + 边框

  content-box: {
    "x": 8,
    "y": 8,
    "width": 216,
    "height": 136,
    "top": 8,
    "right": 224,
    "bottom": 144,
    "left": 8
}

  border-box: {
    "x": 8,
    "y": 162.40000915527344,
    "width": 160,
    "height": 80,
    "top": 162.40000915527344,
    "right": 168,
    "bottom": 242.40000915527344,
    "left": 8
}

最后

最近在搞web端自定义打印模板,需要去计算元素的各种属性值,记录下来做知识点的归纳

:trollface:

  • 19
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

$程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值