码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-23 00:12:05      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:获取   asc   char   不用   etl   func   ret   java   image   

代码如下:

<!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>

 

控制台效果

技术分享图片

 

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

标签:获取   asc   char   不用   etl   func   ret   java   image   

原文地址:https://www.cnblogs.com/fanzhanxiang/p/10306687.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!