<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div{padding:100px;}
#div1{background-color: #FFF5EE;position:relative;}
#div2{background-color: #F4F4F4;}
#div3{background-color: #C1FFC1;position:relative;}
</style>
</head>
<body>
<div id="div1">
<div id="div2">
<div id="div3">
</div>
</div>
</div>
<script>
var div3 = document.getElementById("div3");
console.log(div3.offsetParent);
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}
#div1{background-color: #FFF5EE;position:relative;width: 200px;height: 200px;left:30px;top:30px; border:3px solid #7D26CD;}
#div2{background-color: #FF7F00;position:relative;width: 100px;height:100px;left:30px;top:30px; border:3px solid #7D26CD;}
#div3{background-color: #C1FFC1;
position:absolute;
width: 50px;
height: 50px;top:20px;
border:3px solid #7D26CD;
left:0;
transition:1s left;}
</style>
</head>
<body>
<input id = "btn" type="button" value = "点击移动">
<div id="div1">
<div id="div2">
<div id="div3">
</div>
</div>
</div>
<script>
var div3 = document.getElementById("div3");
console.log(div3.offsetParent);
console.log(getComputedStyle(div3).left);
console.log(div3.offsetLeft);
console.log(div3.offsetTop);
var btn = document.getElementById("btn");
btn.onclick = function(){
var left = 0;
var elem = div3;
var div3B = parseInt(getComputedStyle(div3).borderLeftWidth);
while(elem){
left+=elem.offsetLeft+parseInt(getComputedStyle(elem).borderLeftWidth);
elem=elem.offsetParent;
}
left -= div3B;
div3.style.left=-left+"px";
console.log(left);
}
</script>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}
#div1{background-color: #FFF5EE;position:relative;width: 200px;height: 200px;left:30px;top:30px; border:3px solid #7D26CD;}
#div2{background-color: #FF7F00;position:relative;width: 100px;height:100px;left:30px;top:30px; border:3px solid #7D26CD;}
#div3{background-color: #C1FFC1;
position:absolute;
width: 50px;
height: 50px;top:20px;
border:3px solid #7D26CD;
left:0;
transition:1s left;}
</style>
</head>
<body>
<input id = "btn" type="button" value = "点击移动">
<div id="div1">
<div id="div2">
<div id="div3">
</div>
</div>
</div>
<script>
var div3 = document.getElementById("div3");
console.log(div3.offsetParent);
console.log(getComputedStyle(div3).left);
console.log(div3.offsetLeft);
console.log(div3.offsetTop);
var btn = document.getElementById("btn");
btn.onclick = function(){
div3.style.left=-div3.getBoundingClientRect().left+"px";
}
</script>
</body>
</html>