HTMLElement属性:offsetParent,offsetLeft,offsetTop

HTMLElement.offsetParent - Web API 接口参考 | MDN

HTMLElement.offsetParent 是一个只读属性,返回一个指向最近的(指包含层级上的最近)包含该元素的定位元素或者最近的 table,td,th,body元素。当元素的 style.display 设置为 "none" 时,offsetParent 返回 nulloffsetParent 很有用,因为 offsetTop 和 offsetLeft 都是相对于其内边距边界的。

HTMLElement.offsetTop - Web API 接口参考 | MDN

HTMLElement.offsetTop 为只读属性,它返回当前元素相对于其 offsetParent 元素的顶部内边距的距离

HTMLElement.offsetLeft - Web API 接口参考 | MDN

 HTMLElement.offsetLeft 是一个只读属性,返回当前元素左上角相对于  HTMLElement.offsetParent 节点的左边界偏移的像素值。 (行内元素特殊,见文档

JS在线编辑器,JS在线运行,在线演示,调试测试代码

<style>
    * {
        margin: 0
    }
    /* 有position: relative; 和没有时候的区别,子元素对应的offsetParent不一样了 */
    #father {
        /* position: relative;  */
        width: 150px;
        height: 150px;
        background: red;
    }
    #son {
        margin-top: 10px;
        margin-left: 10px;
        width: 50px;
        height: 50px;
        background: blue; 
        line-height: 50px;
        text-align: center;
    }
</style>
<body>
    <div id="father">
        <div id="son">son</div>
    </div>
</body>
<script>
  var son = document.getElementById("son");
  console.log(son.offsetParent)
  console.log(son.offsetLeft)
  console.log(son.offsetTop)
</script> 

垂直方向上的margin相关问题:理解 margin 垂直重叠的原因和解决方案_real_metrix的博客-CSDN博客_垂直margin重叠是为什么

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值