对于offsetWidth,offsetHeight,offsetLeft,offsetTop的理解

如何理解区分offsetWidth,offsetHeight,offsetLeft,offsetTop

在刚开始使用的时候总是不能理解这四个有什么不一样,用在哪里,因为这几个词真的太像了,emmm,总结了一番,谈谈我的理解
这里首先说一下offsetWidth和offsetHeight
offsetWidth:指的是自身的宽
offsetheight:指的是自身的高
附上代码理解:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
	#box{
		width: 100px;
		height: 100px;
		padding: 10px;
		border:10px solid #000;
		background: red;
	}
</style>
</head>
<body>
	<div id="box"></div>
	<script type="text/javascript">
		var oBox=document.querySelector('#box')
		console.log(oBox.offsetWidth,oBox.offsetHeight)
	</script>
</body>
</html>

打印的结果为140 140
加上margin结果仍为140 140
这里可以总结出两点:
1.offsetWidth和offsetHeight没有单位
2.offsetWidth=width+padding+border
offsetHeight=height+padding+border

然后来说一下对offsetLeft,offsetTop的理解
offsetLeft:DOM对象的左边距离定位父级(最近有定位属性的父级)的左边的距离
offsetTop:DOM对象的上边距离定位父级(最近有定位属性的父级)的上边的距离
附上代码理解:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
	#box{
		width: 100px;
		height: 100px;
		padding: 10px;
		border:10px solid #000;
		background: red;
	}
</style>
</head>
<body>
		<div id="box"></div>
	<script type="text/javascript">
		var oBox=document.querySelector('#box')
		console.log(oBox.offsetLeft,oBox.offsetTop)
	</script>
</body>
</html>

打印的结果为8 8
emmm…为什么结果为8呢,我们来看下css样式在这里插入图片描述
发现是body距离最外部有一个8px的距离,所以应该猜测一下应该是oBox距离最外部的左边和上边的距离

此时,在上面的html中加代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
	#outer{
		position:relative
	}
	#box{
		width: 100px;
		height: 100px;
		padding: 10px;
		border:10px solid #000;
		margin-left:100px ;
		background: red;
	}
</style>
</head>
<body>
	<div id="outer">
		<div id="box"></div>
	</div>
	<script type="text/javascript">
		var oBox=document.querySelector('#box')
		console.log(oBox.offsetLeft,oBox.offsetTop)
	</script>
</body>
</html>

震惊的是!!给父元素加上定位后offsetLeft和offsetTop居然变成了100,0,此时联系下刚才的结果,想到上面加定位的父元素是html,这个加定位的元素是outer,所以得出以下结论:
offsetLeft:DOM对象的左边距离定位父级(最近有定位属性的父级)的左边的距离
offsetTop:DOM对象的上边距离定位父级(最近有定位属性的父级)的上边的距离

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值