jQuery get the location of an element relative to window

后端 未结 7 1562
小鲜肉
小鲜肉 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:52

    Try the bounding box. It's simple:

    var leftPos  = $("#element")[0].getBoundingClientRect().left   + $(window)['scrollLeft']();
    var rightPos = $("#element")[0].getBoundingClientRect().right  + $(window)['scrollLeft']();
    var topPos   = $("#element")[0].getBoundingClientRect().top    + $(window)['scrollTop']();
    var bottomPos= $("#element")[0].getBoundingClientRect().bottom + $(window)['scrollTop']();
    

提交回复
热议问题