版权声明:版权所有,如需引用,请注明出处! https://blog.csdn.net/DHRMM999/article/details/82468151
<style type="text/css">
*{
padding: 0;
margin: 0;
}
#box{
width: 100px;
height: 100px;
padding: 10px;
border: 10px solid red;
margin: 100px;
background: pink;
}
.box1{
width: 300px;
height: 300px;
padding: 120px;
margin: 100px;
position: relative;
background: pink;
}
.box2{
width: 100px;
height: 100px;
background: red;
}
</style>
<body>
<!--<div id="box"></div>-->
<div class="box1">
<div class="box2" style="position:fixed">
<div class="box3"></div>
</div>
</div>
</body>
<script type="text/javascript">
//宽高
//var box = document.getElementById("box");
//offsetHeight和offsetWidth可以检测出盒子的高宽,包括高宽本身,padding,border不但包括margin
//console.log(box.offsetHeight,box.offsetWidth)
//左上距离
var box2 = document.getElementsByClassName("box2")[0];
//console.log(box2.offsetLeft,box2.offsetTop)
//1.offsetLeft可以返回没有定位盒子的距离左侧的位置,如果父亲盒子没有,则返回据body的距离,style.left只能获取行内式,如果没有返回“”;
//2.offsetTop返回的是数字。而style.top返回的是字符串,出数字外还带有px;
//3.offsetTop是只读,而style.top是可读写(只读是获取值,可读写是赋值)offsetLeft/Top只能获取值,style.top/left可赋值
//4.如果没有HTML元素指定过TOP样式,则style.top返回的是空字符串。
//带有定位的盒子
//如果父亲盒子没有定位返回body,如果有返回最近的父亲盒子
var box3 = document.getElementsByClassName("box3")[0];
console.log(box3.offsetParent);
</script>