【html】offsetParent-->offsetleft&offsettop

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)
  }

Chrome
Firefox

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值