开发者

Calculating absolute position of HTML element not working

After searching on the internet, I have got these standard methods for finding the actual position of an HTML element. Something like this:

function findPos(obj) {
    var curleft = curtop = 0;
开发者_开发问答    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }

    return [curleft,curtop];
}        

I am using it to find position of the 'Like' button on any YouTube video's page, so that I can insert my own 'div' there (using GreaseMonkey). It works perfectly on the simple Youtube version, but not on cosmicpanda version of it(youtube.com/cosmicpanda). It's way off in that case. Could someone help me knowing why doesn't it work there?

-

Thanks,

Piyush


offsetLeft and offsetTop give you positions relative to the positioned parent, not relative to the entire document.

Your function will have to keep getting offsets recursively until they return null, meaning you're at the document level. Then add up all the offsets together to get the total offset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜