JavaScript CSS Modify Learning Chapter One find location _ basics

Source: Internet
Author: User
Offset
The offsettop and offsetleft two attributes of the elements in all browsers are useful. They will give you the coordinates of the element relative to the parent element.

This code looks up offsetparent, and then adds offsettop and offsetleft. Eventually, no matter where offsetparent is, he will give you the real coordinates of the element on the screen.

Explain
This code is very simple. First pass in the element to be evaluated, then set the variable curleft and curtop to 0.

Copy Code code as follows:
function Findpos (obj) {
var curleft = curtop = 0;

If the browser supports offsetparent:

Copy Code code as follows:
if (obj.offsetparent) {

Every time we find a new object, add his offsettop and offsetleft to Curtop and Curleft:

Copy Code code as follows:
do {
Curleft + = Obj.offsetleft;
Curtop + = Obj.offsettop;

Tip: Return the value of ' = '
Here's the trick:

Copy Code code as follows:
while (obj = obj.offsetparent);

This is not an expression error. I don't want to use ' = = ' to compare obj and obj.offsetparent (that's not going to work because an element is definitely not equal to his parent element).

So I use ' = ' to pass the value of Obj.offsetparent to obj. Here I have a detailed explanation of this technique.

Easy to return
This loop ends when the element has no offsetparent. When offsetparent exist, they will still add offsetleft to the Curleft and add offsettop to the curtop.

When looping technology, we return the coordinates to the program that calls the function.

Copy Code code as follows:
return [Curleft,curtop];}



Translation Address: http://www.quirksmode.org/js/findpos.html

Reprint please keep the following information
Author: North Jade (TW: @rehawk)
Related Article

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.