jQuery get the location of an element relative to window

后端 未结 7 1572
小鲜肉
小鲜肉 2020-11-28 01:20

Given an HTML DOM ID, how to get an element\'s position relative to the window in JavaScript/JQuery? This is not the same as relative to the document nor offset parent sinc

7条回答
  •  盖世英雄少女心
    2020-11-28 01:48

        function trbl(e, relative) {
                var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);
    
                return {
                        t : r.top    + relative['scrollTop'] (),
                        r : r.right  + relative['scrollLeft'](),
                        b : r.bottom + relative['scrollTop'] (),
                        l : r.left   + relative['scrollLeft']() 
    
                }
        }
    
        // Example
        trbl(e, window);
    

提交回复
热议问题