css中offsetTop, offsetHeight,clientHeight,scrollTop,scrollHeight的区别

一、前言

元素大小平时在开发中或多或少都有用到,时常在各种属性中犹豫不决,不知道该用哪个,现在来对偏移量(offsetTop),客户区大小(clientTop),滚动大小(scrollTop)和确定元素大小(getBoundingClientRect().top)做个总结。

二、分析

offsetTop:元素的上外边框至包含元素的上内边框之间的像素距离。这句话主要的点在于包含元素,包含元素的引用保存在offsetParent中,offsetParent不等同于parentNode,例如,td元素的offsetParent是table元素。平时我们将某个元素的position设为relactive,那么他的子元素的offsetParent就是该元素,offsetTop则为该元素的上外边框到offsetParent元素的下内边框的距离,如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        
        .inside-bor {
            position: relative;
            box-sizing: content-box;
            border: 10px solid #cccccc;
            width: 100px;
            height: 100px;
        }
        
        .outer-bor {
            box-sizing: content-box;
            border: 10px solid goldenrod;
            width: 100px;
            height: 100px;
        }
    </style>
</head>

<body>
    <div style="width: 100px;height: 100px;background-color: chartreuse"></div>
    <div class='inside-bor' id="parent">
        <div>
            <div id="children" class="outer-bor">我我我</div>
        </div>
    </div>
    <script>
        console.log(document.getElementById('children').offsetTop);
        console.log(document.getElementById('children').offsetParent);
    </script>
</body>

</html>

offsetHeihgt:包含边框,内边距和内容的高度。

clientHeight:内容加内边框的高度。

scrollTop:被隐藏在内容区域上方的像素。

scrollHeight:在没有滚动条的情况下,元素内容的总高度。

getBoundingClientRect():有4个属性,top,left,right,bottom。都是相对于浏览器视口的像素。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值