获取元素偏移量

95 阅读1分钟

获取元素偏移量

*获取元素偏移量

//     样式
//   <style>
//         * {
//             padding: 0;
//             margin: 0;
//         }

//         .box1 {
//             width: 400px;
//             height: 400px;
//             background-color: pink;
//             position: relative;
//         }

//         .box2 {
//             width: 100px;
//             height: 100px;
//             background-color: skyblue;
//             position: absolute;
//             left: 100px;
//             top: 200px;
//         }
//     </style>
//      对应的   HTML 结构
//      <div class="box1">
//         <div class="box2"></div>
//     </div>





        // 0. 获取元素
        var box2 = document.querySelector('.box2')

        // 1. 获取元素相对父级      元素.offsetParent
        console.log(box2.offsetParent)


        // 2. 获取元素的偏移量
        console.log('box2.offsetLeft', box2.offsetLeft)
        console.log('box2.offsetTop', box2.offsetTop)