offsetWidth与offset Height、offsetLeft与offsetTop详解

本文详细解析了offset系列属性,包括offsetHeight、offsetWidth、offsetLeft、offsetTop及offsetParent的使用方法与特点。通过实例展示了这些属性如何测量元素的尺寸与位置,特别是它们与元素的padding、border以及定位之间的关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

offsetWidth与offset Height、offsetLeft与offsetTop详解 

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>offset</title>
	<style>
		* {
			margin: 0;
			padding: 0;
		}
		.box1 {
			width: 300px;
			height: 300px;
			padding: 100px;
			margin-left: 100px;
			margin-top: 100px;
			background: #d00;
			position: relative;
		}
		.box2 {
			width: 100px;
			height: 100px;
			background: #d0d;
			position: absolute;
			/*left: 100px;*/
		}
	</style>

</head>
<body>
	<div class="box1">
		<div class="box2">
			<div class="box3"></div>
		</div>
	</div>
</body>
<script>
	var box1 = document.getElementsByClassName('box1')[0];
	var box2 = document.getElementsByClassName('box2')[0]
	var box3 = document.getElementsByClassName('box3')[0]
	//offsetHeight和offsetWidth
	/**
	* offsetHeight和offsetWidth监测盒子的宽高
	* 包括本身、padding、border, 不包括margin
	* offsetHeight = width + paddling-top + padding-bottom + border-top + border-bottom 
	*/
	console.log(box1.offsetHeight)
	// offsetLeft和offsetTop
	/**
	* offsetLeft和offsetTop监测距离父盒子有定位的左/上的距离
	* 返回上级盒子(有定位的)左边的位置
	* 如果先辈没有定位则以body为基准
	* offsetLeft从先辈有定位的padding开始计算(border不算)
	* offsetLeft = style.left(没有px)
	*/
	//offsetLeft与style.left区别
	/**
	* 1.最大区别在于offsetLeft可以返回没有定位盒子的距离左侧的位置(若父辈没有定位,offsetLeft以body为准;style.left则返回空字符串)
	* 2.offsetLeft 返回的是数字,style.left返回的是字符串,除了数字以外带有单位px
	* 3.offsetLeft 只读,style.left可读写,(只读是获取值,可读写是赋值)
	* 4.如果没有给HTML元素指定top样式,则style.left返回空字符串
	*/

	console.log(box2.offsetLeft)

	//offsetParent
	/**
	* offsetParent 监测父辈盒子中带有定位的的盒子
	* 父辈盒子中没有定位,返回body
	* 若有返回最近的
	*/
	console.log(box3.offsetParent)
</script>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值