js算法之获取DOM节点的绝对位置
Posted fanzhanxiang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
控制台效果
以上是关于js算法之获取DOM节点的绝对位置的主要内容,如果未能解决你的问题,请参考以下文章