how to find the vertical distance from top in px of an element using jQuery

前端 未结 4 1085
时光取名叫无心
时光取名叫无心 2021-01-30 09:52

How do I find the vertical distance from the top of the page to where the element exist in the DOM using javascript/jQuery?

I\'ve something like



        
相关标签:
4条回答
  • As far as i know .offset() get the distance between the current scroll position and the top of the document.

    You need to use this: $("li.test").position().top

    0 讨论(0)
  • 2021-01-30 10:38

    Use .offset() to get the distance between an element and the top of the document:

    $("li.test").offset().top
    
    0 讨论(0)
  • 2021-01-30 10:46

    Rob W's answer is correct - that will give you the offset from the top of the full page.

    If you want to get the offset from the top of the viewable screen, you should do this:

    var viewableOffset = $("#li.test").offset().top - $(window).scrollTop();
    

    Hope that helps!

    0 讨论(0)
  • 2021-01-30 10:52

    Use $(element).offset().top and add height of existing fixed elements on the page to it to make it more accurate.

    0 讨论(0)
提交回复
热议问题