offsetParent
HTMLElement.offsetParent 是一个只读属性,返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table,td,th,body元素。当元素的 style.display 设置为 “none” 时,offsetParent 返回 null。offsetParent 很有用,因为 offsetTop 和 offsetLeft 都是相对于其内边距边界的。
offsetParent
1.父级是否有定位(4种 absolute relative fixed sticky)
2. 本身是否有定位(4种)
3. 浏览器不一样(5大pc浏览器 + ie678 = 8种)
本身定位为fixed
==> offsetParent:null(不是火狐)
==> offsetParent:body(火狐)
本身定位不为fixed
父级没有定位
==> offsetParent:body
父级有定位
==> offsetParent:定位父级
window.onload = function(){
console.log(inner3.offsetParent.id)
}
offsetleft&offsettop
一般开发时会加上如下代码,习惯性让body当整个视口,因为很多api的视口都是参照body的。——>清除系统默认滚动条
html,body{
height: 100%;
overflow: hidden;
}
// code
<!DOCTYPE html>
<html id="html" lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,body{
height: 100%;
overflow: hidden;
}
#wrap{position: absolute;background-color: pink;left:100px;top: 50px;}
#inner1{position: fixed;background-color: deeppink;left:50px;top:150px}
#inner2{position: relative;background-color: lightgreen;left:80px;top:70px}
#inner3{position: fixed;background-color: green;left:60px;top:30px}
div{
width: 200px;
height: 200px;
}
</style>
</head>
<body id="body">
<div id="wrap">wrap
<div id="inner1">inner1
<div id="inner2">inner2
<div id="inner3">inner3</div>
</div>
</div>
</div>
</body>
<script>
/* 兼容性问题
ev||event
鼠标滚轮
事件绑定
offsetParent
1.父级是否有定位(4种 absolute relative fixed sticky)
2. 本身是否有定位(4种)
3. 浏览器不一样(5大pc浏览器 + ie678 = 8种)
###offsetParent(如果body和html直接的margin被清掉)
本身定位为fixed
==> offsetParent:null(不是火狐)
offsetLeft和offsetTop也是参照body
==> offsetParent:body(火狐)
本身定位不为fixed
父级没有定位
==> offsetParent:body
父级有定位
==> offsetParent:定位父级
###haslayout
ie7以下,如果当前元素的某个父级触发了haslayout,
那么offsetParent就会被指向到这个触发了layout特性的父节点上
###注意点
1.分清parentNode和offsetParent的区别
parentNode:直接父级
offsetParent:类似于css的包含块
2.offsetParent的作用
offsetLeft 和 offsetTop 是参照于offsetParent的内边距边界的
3.dom里所有的元素都是有offsetLeft 和 offsetTop的
*/
window.onload = function(){
console.log(inner3.offsetLeft)
}
</script>
</html>
</html>