样式

div{
			background-color:gray;
			display:flex;
		    justify-content: center;
			align-items: center;
		}
		.box{
		    width:300px;
			height:200px;
			border:1px solid #ccc;
			padding:10px 20px; // 上下10px 左右20px
		}

标签

<body>
<div id="div" class="box">111</div>
</body>

js

const div=document.getElementById("div");

clientHeight 和 clientWidth

 clientHeight 的值 = 元素内容(这里是高度)+上下padding
 clientWidth 的值 = 元素内容(这里是宽度)+左右padding
 clientHeight = height + padding = 200 + 10 * 2 = 220
 clientWidth = width + padding = 300 + 20 * 2 = 340
console.log(div.clientHeight); // 220
console.log(div.clientWidth); // 340

offsetHeight 和 offsetWidth
offsetHeight :元素的实际高度
offsetWidth:元素的实际宽度

 offsetHeight 的值 = 元素内容(这里是高度) + 上下padding + 上下border
 offsetWidth 的值 = 元素内容(这里是宽度) + 左右padding + 左右border
 offsetHeight = height + padding*2 + border*2 = 200 + 10 * 2 + 1 * 2 = 222
 offsetWidth = width + padding*2 + border*2 = 300 + 20 * 2 + 1 * 2 = 342
 console.log(div.offsetHeight); // 222 注意这里返回的值不带有单位(px)
 console.log(div.offsetWidth); // 342 

offsetParent

offsetParent属性返回一个对象的引用,这个对象是距离调用offsetParent的元素最近的(在包含层次中最靠近的),并且是已进行过CSS定位(relative、absolute、fixed)的容器元素。 如果这个容器元素未进行CSS定位, 则offsetParent属性的取值为根元素的引用

console.log(div.offsetParent.tagName); // body

offsetLeft 和 offsetTop
offsetLeft:元素的实际距离左边界的距离
offsetTop:元素的实际距离上边界的距离

  注意:没有 offsetRight 和 offsetBottom
 offsetTop 表示该元素的边框上边缘与它最近父元素的上边框内边缘的距离,
 如果没有父元素则把body当做它的父元   素,由此知(默认情况下body有个margin值8px)
console.log(div.offsetLeft); // 8
console.log(div.offsetTop); // 8

scrollWidth 和 scrollHeight

scrollHeight: 获取对象的滚动高度,包括由于滚动而未显示在屏幕中内容
scrollWidth:获取对象的滚动宽度,包括由于滚动而未显示在屏幕中内容

获取元素中滚动条的宽度

 scrollbarWidth = div.offsetWidth - div.clientWidth

scrollLeft 和 scrollTop

scrollLeft:对象的最左边到对象在当前窗口显示的范围内的左边的距离,即在出现了横向滚动条的情况下,滚动条拉动的距离。
scrollTop:对象的最顶部到对象在当前窗口显示的范围内的顶边的距离,即在出现了纵向滚动条的情况下,滚动条拉动的距离。

getBoundingClientRect获取height和width

 注意:getBoundingClientRect获取的height和width 与 offsetHeight 和 offsetWidth 的计算相同
height = 元素内容()+上下padding+上下border
width =  元素内容()+左右padding+左右border  
console.log(div.getBoundingClientRect().height);// 222
console.log(div.getBoundingClientRect().width);// 342
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐