盒模型:主要分为css盒模型和js盒模型俩种
1.什么是CSS盒模型?
CSS盒子模型(Box model)就是在网页设计中经常用到的CSS技术所使用的一种思维模型。网页中所有元素都具备以下四个属性:
- 内容(content),也就是元素的 width、height
- 内边距(padding)
- 边框(border)
- 外边距(margin)
2.盒子模型有哪两种
- 标准模式下: 一个块的总宽度(页面中占的宽度)= width + margin(左右) + padding(左右) + border(左右)
- 怪异模式下: 一个块的总宽度= width + margin(左右)(即width已经包含了padding和border值)(IE浏览器)
3.标准和怪异模型的转换
box-sizing:content-box
; 将采用标准模式的盒子模型标准box-sizing:border-box
; 将采用怪异模式的盒子模型标准box-sizing:inherit
; 规定应从父元素继承 box-sizing 属性的值。
4.JS盒模型
client系列:
- clientWidth/clientHeight
如果不设置容器的宽高,用内边距撑开,获取的是内容的实际宽高加上内边距。如果设置宽高,则高度就是设置的宽高加上内边距。 - clientLeft/clientTop 边框的宽度
var box=document.getElementById("box");
2 console.log(box.clientWidth);
3 console.log(box.clientHeight);
4 console.log(box.clientLeft);
5 console.log(box.clientTop);
offset系列:
- offsetWidth/offsetHeight (clientWidth+clientLeft2),(clientHeight+clientTop2)
- offsetLeft/offsetTop 相对父级盒子的外边距
- offsetParent 盒子的父级盒子
console.log(box.offsetWidth);
console.log(box.offsetHeight);
console.log(box.offsetLeft);
console.log(box.offsetTop);
console.log(box.offsetParent);
scroll系列:
- scrollWidth/scrollHeight 如果内容没有溢出,值和clientWidth/clientHeight一样。
- scrollWidth:实际溢出内容宽度+左填充
- scrollHeight:实际溢出内容高度+上填充
- scrollTop: 滚动条卷去的高度
- scrollLeft: 滚动条卷去的宽度
1 console.log(box.scrollWidth);
2 console.log(box.scrollHeight);
3 console.log(box.scrollTop);
4 console.log(box.scrollLeft);
获取,设置浏览器盒子模型信息兼容写法
document.documentElement.clientWidth||document.body.clientWidth