This article describes how to implement jquery's offset () method in javascript. The example analyzes the principles of jquery's offset () method and the techniques implemented using javascript, which has some reference value, for more information about jquery's offset () method, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
Anyone who has used jQuery offset () knows that offset (). top or offset (). left can easily get the offset of an element relative to the entire page.
In js, there is no such direct method. The Node attribute offsetTop can obtain the relative offset of the node relative to the parent node, but cannot directly obtain the absolute offset, we can use nodes to add offsetTop layer by layer recursion to obtain the absolute offset.
The Code is as follows:
Function getOffset (Node, offset ){
If (! Offset ){
Offset = {};
Offset. top = 0;
Offset. left = 0;
}
If (Node = document. body) {// end recursion when the Node is a body Node
Return offset;
}
Offset. top + = Node. offsetTop;
Offset. left + = Node. offsetLeft;
Return getOffset (Node. parentNode, offset); // accumulate the value in the offset
}
For example:
The Code is as follows:
Var a = document. getElementById ('A ');
// GetOffset (a). top
// GetOffset (a). left
I hope this article will help you design javascript programs.