using javascript to find position of DOM elements

耗尽温柔 提交于 2019-12-08 07:39:34

问题


I want to inspect spatial organization of elements on a web page.

Could I get sample code and pointers to resources.

Thanks.


回答1:


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.




回答2:


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/




回答3:


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



来源:https://stackoverflow.com/questions/7630338/using-javascript-to-find-position-of-dom-elements

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