Js Implementation of jquery's offset () method instance_javascript tips-js tutorial

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.