元素距离页面上的Top和Left

<!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>js获取屏幕高度</title>
    <script src="../js/jquery-3.4.1.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .box1 {
            height: 3000px;
            display: flex;
            justify-content: center;
        }

        .box2 {
            margin-top: 700px;
            width: 100px;
            height: 100px;
            padding: 30px;
            position: relative;
            background-color: aquamarine;
        }

        .box3 {
            width: 70px;
            height: 50px;
            margin: 25px auto 25px auto;
            padding: 10px;
            border: 10px solid red;
            background-color: coral;
        }
    </style>
</head>

<body>
    <div class="box1">
        <div class="box2">
            <div class="box3"></div>
        </div>
    </div>
</body>
<script>

    function box(e) {
        let box2 = document.querySelector('.box2')
        let box2OffsetTop = box2.offsetTop
        let box2OffsetLeft = box2.offsetLeft
        console.log('页面顶部距离', box2OffsetTop);  // 页面顶部距离 700
        console.log('页面左边距离', box2OffsetLeft); // 页面左边距离 680

        // 如果父元素使用position: relative fxied absolute
        let box3 = document.querySelector('.box3')
        let box3OffsetTop = box3.offsetTop
        let box3OffsetLeft = box3.offsetLeft
        console.log('子元素距离父元素的top距离', box3OffsetTop); //子元素距离父元素的top距离 55
        console.log('子元素距离父元素的left距离', box3OffsetLeft); // 子元素距离父元素的left距离 30

        // 子元素距离父元素的距离,注意:这里父元素设置了position: relative fxied absolute;就使用offsetParent就可以定位到父元素上
        let box3OffsetTop3 = box3.offsetParent.offsetTop - box3.offsetTop
        let box3OffsetLeft3 = box3.offsetParent.offsetLeft - box3.offsetLeft
        console.log('父元素设置定位情况下子元素的top位置', box3OffsetTop3); // 父元素设置定位情况下子元素的top位置 645
        console.log('父元素设置定位情况下子元素的left位置', box3OffsetLeft3); // 父元素设置定位情况下子元素的left位置 650

        // 获取元素宽度和高度 包括 padding 不包括 border
        let box3scrollWidth = box3.scrollWidth
        let box3scrollHeight = box3.scrollHeight
        let box3clientWidth = box3.clientWidth
        let box3clientHeight = box3.clientHeight

        console.log('元素宽度', box3scrollWidth); // 元素宽度 90
        console.log('元素高度', box3scrollHeight); // 元素高度 70
        console.log('元素宽度', box3clientWidth); // 元素宽度 90
        console.log('元素高度', box3clientHeight); // 元素高度 70
    }
    box()
</script>

</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值