JavaScript gets the offset value code for the page element

Source: Internet
Author: User

JS acquisition method.

The code is as follows Copy Code

document.getElementById ("Divfloat"). Style.top=document.getelementbyid ("button"). offsetleft+25;


With IETester and Firefox test, under the ie6+ can, as before, write the pure JS method mercilessly despised by Firefox, get the value is not correct.

On the internet again, found that should be so written, through the loop, layers upward calculation, and finally get the correct value of the offset.

JS gets the offset value of the Web page control method

The code is as follows Copy Code

Colour Pallete Top Offset
function Getoffsettop (Elm) {
var moffsettop = elm.offsettop;
var moffsetparent = elm.offsetparent;
while (moffsetparent) {
Moffsettop + = Moffsetparent.offsettop;
Moffsetparent = moffsetparent.offsetparent;
}
return moffsettop;
}

Colour Pallete left Offset
function Getoffsetleft (Elm) {
var moffsetleft = Elm.offsetleft;
var moffsetparent = elm.offsetparent;
while (moffsetparent) {
Moffsetleft + = Moffsetparent.offsetleft;
Moffsetparent = moffsetparent.offsetparent;
}
return moffsetleft;
} function Ie_y (e) {
var t=e.offsettop;
while (e=e.offsetparent) {
T+=e.offsettop;
}
return t;
}
function Ie_x (e) {
var l=e.offsetleft;
while (e=e.offsetparent) {
L+=e.offsetleft;
}
return l;
}


the implementation of jquery

One more step to find out about the problem is that jquery already contains functions to implement this functionality: offset (), which is well compatible with browsers.

The code is as follows Copy Code

$ ("#Button"). Offset (). Left

The individual prefers to use the jquery feature because the code is simple and straightforward and compatible.

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.