Home > Article > Web Front-end > How to get the distance from DOM node to the top or left side of the browser in js
How to get the distance from the DOM node to the top or left side of the browser in js? This article will introduce to you how to get the distance from the DOM node to the top or left side of the browser using js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
About js to get the distance from the dom node to the top or left of the browser, there is an encapsulated offset().top/offset().left in Jquery, which is only the distance to the top/left of the parent position ().top/position().left. [Recommended tutorial: JavaScript Video Tutorial]
If you write it natively, just use the get node and do while loop. The code is as follows
<!DOCTYPE html> <html> <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>原生JS获取DOM 节点到顶部的距离</title> </head> <body> <ul> <li>11111</li> <li>11111</li> <li>11111</li> <li>11111</li> <li id="item">11111</li> </ul> <script> var dom = document.getElementById('item'); var iTop = 0; do { iTop += dom.offsetTop;//如果是左侧就是offsetLeft dom = dom.parentNode //如果DOM 节点 的parentNode存在,把当前的节点赋予成parentNode; } while (dom.parentNode); console.log(iTop) </script> </body> </html>
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to get the distance from DOM node to the top or left side of the browser in js. For more information, please follow other related articles on the PHP Chinese website!