JS盒子模型

盒子模型:

    // 1.clientWidth: 内容宽度+左右padding
    // 2.clientHeight:内容的高度+上下padding
    // console.log(box.clientWidth) // 540
   // 3.clientLeft :左边框的宽度
   // 4.clientTop :上边框的高度
    //5.offsetWidth: 盒子总宽度;
    // clientWidth+左右border+内边距
    //6.offsetHeight:盒子的高度  
    // console.log(box.offsetWidth);// 560
    // 有溢出的情况
    // 7.scrollWidth :内容实际宽度+一个左padding
    // 8.scrollHeight: 内容实际高度+一个上padding
    // 如果没有溢出;scrollHeight和clientHeight相等;

复制代码

body {
    margin: 0;
    padding: 0;
}
.box {
    position: absolute;
    margin: 10px;
    padding: 10px;
    width: 100px;
    height: 100px;
    border: 10px solid #000;
    line-height: 25px;
}

复制代码

1.client系列

clientWidth/clientHeight 如果不设置容器的宽高,用内边距撑开,获取的是内容的实际宽高加上内边距。如果设置宽高,则高度就是设置的宽高加上内边距。
clientLeft/clientTop 边框的宽度

1 var box=document.getElementById("box");
2 console.log(box.clientWidth); //120
3 console.log(box.clientHeight); //120
4 console.log(box.clientLeft); //10
5 console.log(box.clientTop); //10

2.offset系列

offsetWidth/offsetHeight (clientWidth+clientLeft2),(clientHeight+clientTop2)
offsetLeft/offsetTop 相对父级盒子的外边距
offsetParent 盒子的父级盒子

1 console.log(box.offsetWidth); //140
2 console.log(box.offsetHeight); //140
3 console.log(box.offsetLeft); //10
4 console.log(box.offsetTop); //10
5 console.log(box.offsetParent); //body

3.scroll系列

scrollWidth/scrollHeight 如果内容没有溢出,值和clientWidth/clientHeight一样。如果内容溢出:
scrollWidth:实际溢出内容宽度+左填充
scrollHeight:实际溢出内容高度+上填充
scrollTop: 滚动条卷去的高度
scrollLeft: 滚动条卷去的宽度

1 console.log(box.scrollWidth); //120
2 console.log(box.scrollHeight); //120
3 console.log(box.scrollTop);  //0
4 console.log(box.scrollLeft); //0
获取,设置浏览器盒子模型信息兼容写法
document.documentElement.clientWidth||document.body.clientWidth

封装一个函数获取设置盒子模型

1 function win(attr, value) {
2     if(typeof value === "undefined") {
3         return document.documentElement[attr] || document.body[attr];
4     }
5     document.documentElement[attr] = value;
6     document.body[attr] = value;
7 }

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值