jQuery get the location of an element relative to window

后端 未结 7 1560
小鲜肉
小鲜肉 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 02:01

    TL;DR

    headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();
    
    headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe
    

    .getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

提交回复
热议问题