DOM元素尺寸获取

offset

获取盒模型的尺寸,可视宽高 包含边框

<div>
     <p></p>
</div>

    <script>
        var box = document.querySelector('div');
        var p = document.querySelector('p');

        // 盒模型的宽度  包含边框
        console.log(box.offsetWidth);
        console.log(box.offsetHeight);

        // 获取相对于(定位)父级的left   定位父级
        console.log(box.offsetLeft);
        console.log(box.offsetTop);
        console.log(p.offsetLeft);
    </script>

client

可视宽高度 不包含边框 即自身内容尺寸

        // 不包含border 可视宽高度 自身内容尺寸
        console.log(box.clientWidth);
        console.log(box.clientHeight)

        // 上边框宽度
        console.log(box.clientTop)  //上边框宽度
        console.log(box.clientLeft)   //左边框宽度

scroll

也是自身内容尺寸 但包含 滚动条滚动的尺寸

        // 内容宽度   这里用在box上面时 和上面的 clientWidth可视区显示的结果是一样的
        console.log(box.scrollWidth);
        console.log(box.scrollHeight);

scroll和client的区别

当我们在用定义的box计算其scrollWidth和clientWidth时发现结果一样,都是计算其自身内容的尺寸(不包含边框),但是 如果是用在计算整个页面的width时(有滚动条的情况下) 两者的显示结果会不一样 client只计算当前可视区的尺寸 而 scrollwidth还可以计算包括滚动条在内的尺寸大小

        // 当前浏览器可视区宽度  不包括页面滚动的宽度高度
        console.log(document.documentElement.clientWidth);
        console.log(document.documentElement.clientHeight)
        // console.log(document.documentElement.clientHeight);


        // 内容高度  有滚动条时会更明显
        console.log(document.documentElement.scrollHeight)
        console.log(document.documentElement.scrollWidth)

getBoundingClientRect()

getBoundingClientRect()用于获得页面中某个元素的左,上,右和下分别相对浏览器可视区的位置 (也就是相对于页面的左上角)。这个方法没有参数。它会返回一个Object对象,该对象有6个属性:left right top bottom width height


        var box = document.querySelector('div');
        window.onscroll = function(){

            // getBoundingClientRect()
            var clientRect = box.getBoundingClientRect();
            
            //可视区相对位置

            console.log(clientRect);
            console.log(clientRect.left);   //元素左侧距离可视区左侧的距离
            console.log(clientRect.top);   //元素顶部距离可视区域的距离
            console.log(clientRect.bottom);  //元素底部距离可视区域的距离
            console.log(clientRect.right);  //元素右侧距离可视区左侧的距离

            console.log(clientRect.width);   //可视宽度
            console.log(clientRect.height);   //可视高度
            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值