Home > Article > Web Front-end > js implementation of jquery’s offset() method example_javascript skills
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.
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
}
, it is as follows:
I hope this article will be helpful to everyone’s JavaScript programming design.