using javascript to find position of DOM elements

若如初见. 提交于 2019-12-07 18:55:46

If you want good, modular code that you can read and easily extract just the bits you want, try David Mark's MyLibrary (which you use to build your library).

I find libraries like jQuery are so intricately bound up in themselves and dependant on their own functionality that trying to track down all the functions and re-mapping of properties is an exercise in frustration. On the other hand, MyLibrary is written to be very modular from the start and provides better cross-browser features.

Here you go:

function position( elem ) {
    var left = 0,
        top = 0;

    do {
        left += elem.offsetLeft;
        top += elem.offsetTop;
    } while ( elem = elem.offsetParent );

    return [ left, top ];
}

Live demo: http://jsfiddle.net/dDyZF/2/

You didn't ask for jQuery, but you might want to check out the jQuery dimensions plugin.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!