JavaScript:offsetParent

  • offsetParent获取到的是某个元素的具有定位属性的父节点,直到寻到<body>为止。下面获取#div2offsetParent,由于#div1没有设置定位属性,故而div2获取到的offsetParentbody
<!DOCTYPE html>
<html>
<head>
	<title>learn js</title>
<style type="text/css">
	#div1{
		width: 200px;
		height: 200px;
		background-color: gray;
	}
	#div2{
		width: 100px;
		height: 100px;
		background-color: red;
	}
</style>
<script type="text/javascript">
	window.onload = function(){
		var div2 = document.getElementById('div2');
		alert(div2.offsetParent)
	};
</script>
</head>

<body>
	<div id="div1">
		<div id="div2"></div>
	</div>
</body>
</html>
  • 接下来在#divcss样式中加入position: absolute; 或者 position: relative; #div2获取到的offsetParent都将是#div1
posted @ 2020-02-09 17:04  昨夜昙花  阅读(10)  评论(0)    收藏  举报