Home > Web Front-end > JS Tutorial > body text

js implementation of jquery's offset() method example_javascript skills

WBOY
Release: 2016-05-16 16:21:19
Original
1190 people have browsed it

The example in this article describes how js implements the offset() method of jquery. Share it with everyone for your reference. The specific analysis is as follows:

Students who have used jQuery's offset() know that offset().top or offset().left can easily obtain the offset of an element relative to the entire page.

In js, there is no such direct method. The node's attribute offsetTop can obtain the relative offset of the node relative to the parent node, but cannot directly obtain its absolute offset. We can use the nodes to recurse upward layer by layer and add them up. offsetTop to get the absolute offset.

Copy code The code is as follows:
function getOffset(Node, offset) {
If (!offset) {
Offset = {};
Offset.top = 0;
Offset.left = 0;
}

if (Node == document.body) {//When the node is the body node, end the recursion
         return offset;
}

offset.top = Node.offsetTop;
Offset.left = Node.offsetLeft;

return getOffset(Node.parentNode, offset); // Accumulate the value in offset upwards
}


When using

, it is as follows:

Copy code The code is as follows:
var a = document.getElementById('a');
//getOffset(a).top
//getOffset(a).left

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
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