Home > Web Front-end > JS Tutorial > 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 DOM node to the top or left side of the browser in js

青灯夜游
Release: 2019-01-05 11:40:02
forward
6108 people have browsed it

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>
Copy after login

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!

Related labels:
js
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template