getBoundingClientRect方法获取盒子的相关长度属性

js的getBoundingClientRect方法获取盒子的相关长度属性

getBoundingClientRect可以获取盒子本身的宽度和高度以及盒子的四个边框即top、bottom、right、left到浏览器左窗口和上窗口的距离。

通过rect = domNode.getBoundingClientRect()来获取盒子的相关属性对象。

​ rect.left: 50 //盒子左边框到浏览器当前左窗口的距离
​ rect.right: 350 // 盒子又边框到浏览器当前左窗口的距离
​ rect.top: 50 // 盒子的上边框到浏览器当前上窗口的距离
​ rect.bottom: 350 //盒子的下边框到浏览器当前上窗口的距离
​ rect.width: 300 //盒子的宽度
​ rect.height: 300 //盒子的高度
​ rect.x: 50
​ rect.y: 50//(x, y)是盒子的左顶点到浏览器当前窗口左顶点的距离

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

<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>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    div {
        width: 300px;
        height: 300px;
        border: 2px solid pink;
        margin: 50px 50px;
        box-sizing: border-box;
    }
</style>

<body>
    <div></div>
</body>
<script>
    let div = document.querySelector("div")
    let rect = div.getBoundingClientRect()
    console.log(rect);
    /*
    left: 50 //盒子左边框到浏览器左窗口的距离
    right: 350 // 盒子又边框到浏览器左窗口的距离
    top: 50 // 盒子的上边框到浏览器上窗口的距离
    bottom: 350 //盒子的下边框到浏览器上窗口的距离
    width: 300  //盒子的宽度
    height: 300 //盒子的高度
    x: 50 
    y: 50//(x, y)坐标是盒子的左顶点到浏览器窗口左顶点的距离
    */
    console.log(div.scrollHeight);
</script>

</html>

image-20220322221436940

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

veggie_a_h

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值