<!-- 使用offsetParent
距离该子元素最近的进行过定位的父元素(position:absolute relative fixed),
如果其父元素中不存在定位则offsetParent为:body元素 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.outer {
width: 300px;
height: 300px;
background-color: green;
position: relative;
}
.inner {
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
}
</style>
<script>
window.onload = function () {
var oinner = document.getElementsByClassName("inner")[0];
console.log(oinner.offsetParent);
// <div class="outer">
// <div class="inner"></div>
// </div>
}
</script>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
使用offsetParent
最新推荐文章于 2024-04-28 08:32:47 发布