- offsetParent获取到的是某个元素的具有定位属性的父节点,直到寻到<body>为止。下面获取#div2的offsetParent,由于#div1没有设置定位属性,故而div2获取到的offsetParent是body
<!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>
- 接下来在#div的css样式中加入position: absolute; 或者 position: relative; #div2获取到的offsetParent都将是#div1