原生js中offsetTop, offsetLeft与offsetParent的详细讲解

简单说下:offsetTop

 offsetTop: 为只读属性。 返回的是一个数字。
它返回当前元素相对于其 offsetParent 元素的顶部内边距的距离。
它等价于offsetTop==>元素到offsetParent顶部内边距的距离
offsetTop并不是指距离浏览器窗口最左边的位置。
我的理解:offsetTop的偏移是指当前元素相对其距离自己最近的具有定位属性的父级元素的偏移值。
margin:会影响它的值。 定位的值会影响。 border也会影响。但是padding不会影响。
offsetLeft跟offsetTop是一样的。他们是一对的。

offsetTop 的简单使用

 <body>
<div id="title">
我是标题
</div>
<div id="nav">
我是导航
</div>
<div id="cont">
我是内容
</div>
</body>
<script>
let cont = document.getElementById('cont')
let dingbuTop = cont.offsetTop;
console.log('dingbuTop', dingbuTop); //输出的是50
/* 之所以是50=21+21+*
div的默认高度是21;有两个div。 body的外边距margin:8px;
*/
</script>

margin 会影响它的值(margin-bottom也不会), border也会影响,padding不会

 <style>
#cont {
padding: 10px;
background: red;
margin-top: 50px;
}
</style>
<body>
<div id="title">
我是标题
</div>
<div id="nav">
我是导航
</div>
<div id="cont">
我是内容
</div>
</body>
<script>
let cont = document.getElementById('cont')
let dingbuTop = cont.offsetTop;
// body的外边距margin:8px;div的默认高度是21;有两个div。
//padding 并没有影响它的值
console.log('dingbuTop', dingbuTop); //输出的是 8+21+21+50=100
</script>

定位会影响它的值

 <style>
#cont {
background: red;
position: absolute;
top: 150px;
left: 150px;
}
</style>

<body>
<div id="title">
我是标题
</div>
<div id="nav">
我是导航
</div>
<div id="cont">
我是内容
</div>
</body>
<script>
let cont = document.getElementById('cont')
let dingbuTop = cont.offsetTop;
console.log('dingbuTop', dingbuTop); //输出的是150
</script>

当前元素相对其距离自己最近的具有定位属性的父级元素的偏移

 <style>
#cont {
margin-top: 100px;
position: relative;
}
#son {
background: pink;
position: absolute;
left: 10px;
top: 10px;
}
</style>
<body>
<div id="cont">
<div id="son">
son
</div>
</div>
</body>
<script>
let son = document.getElementById('son')
let dingbuTop = son.offsetTop;
console.log('dingbuTop', dingbuTop); //输出的10
</script>

子绝父相-子元素距离屏幕顶部的距离

 <style>
#cont {
margin-top: 100px;
position: relative;
background: #000;
}
#son {
background: pink;
position: absolute;
left: 10px;
top: 10px;
}
</style>
<body>
<div id="cont">
<div id="son">
son
</div>
</div>
</body>
<script>
let son = document.getElementById('son')
let dingbuTop = son.offsetTop + son.offsetParent.offsetTop;
console.log('dingbuTop', dingbuTop); //输出的是 110
</script>

offsetParent

 HTMLElement.offsetParent 是一个只读属性.
返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table, td, th, body 元素。
当元素的 style.display 设置为 "none" 时,offsetParent 返回 null。

等价于offsetParent:返回指向最近的一个具有定位的祖宗元素(relative,absolute,fixed)。
若祖宗都不符合条件,offsetParent为body。

<div id="cont">
<div id="son1">
son1
</div>
<div id="son">
son
</div>
</div>

let son = document.getElementById('son')
let ele = son.offsetParent;
console.log('ele', ele); // 输出的是body这个元素 若祖宗都不符合条件,offsetParent为body。

标签: Javascript

添加新评论