js算法之获取DOM节点的绝对位置

代码如下:

<!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>绝对位置</title>
    <style type="text/css">
        .box1 {
            position: absolute;
            top: 10px;
            left: 10px;
            width: 200px;
            height: 200px;
            background-color: blue;
        }

        .box1 .box2 {
            position: absolute;
            top: 100px;
            left: 100px;
            width: 200px;
            height: 200px;
            background-color: brown;
        }

        .box1 .box2 #box {
            position: absolute;
            top: 100px;
            left: 100px;
            width: 200px;
            height: 200px;
            background-color: chartreuse;
            border: 2px solid #ddd;
        }
    </style>
</head>

<body>
    <div class='box1'>
        <div class='box2'>
            <div id='box'></div>
        </div>
    </div>
    <script type="text/javascript">
        // 用递归的思想来做
        function get_layout(ele) {
            const layout = {
                // offsetWidth包含border
                // clientWidth包含border
                width: ele.offsetWidth,
                height: ele.offsetHeight,
                left: ele.offsetLeft,
                top: ele.offsetTop
            }
            if (ele.offsetParent) {
                const parentLayout = get_layout(ele.offsetParent)
                layout.left += parentLayout.left
                layout.top += parentLayout.top
            }
            return layout
        }

        // 不用递归
        function get_layout(ele) {
            let left = ele.offsetLeft,
                top = ele.offsetTop
            let p = ele.offsetParent
            while (p) {
                left += p.offsetLeft
                top += p.offsetTop
                p = p.offsetParent
            }
            return {
                width: ele.offsetWidth,
                height: ele.offsetHeight,
                left: left,
                top: top
            }
        }
        let getBox = document.getElementById('box')
        console.log(get_layout(getBox))
    </script>
</body>

</html>

控制台效果

猜你喜欢

转载自www.cnblogs.com/fanzhanxiang/p/10306687.html