找到div顶部和窗口底部之间的高度

找到div顶部和窗口底部之间的高度

问题描述:

使用jQuery,我如何找到任何div顶部和视口底部之间的高度?找到div顶部和窗口底部之间的高度

在我的代码中,我需要在滚动时主动找到页脚顶部和窗口底部之间的距离。

任何想法如何做到这一点?

+0

请参阅[this](http://stackoverflow.com/questions/9880472/determine-distance-from-the-top-of-a-div-to-top-of-window-with-javascript)所以我接受了答案,希望这会有所帮助。 – 2016-01-26 01:42:51

一个简单的方法:

function updateScroll() { 
    // the div whose offset we're measuring: 
    var measure = $('#measure'), 
    // the height of the window: 
     windowHeight = $(window).height(), 
    // the scroll-distance of the window: 
     scrollDistance = $(window).scrollTop(), 
    // how far from the 'top' of the document the div element is: 
     divOffsetTop = measure.offset().top, 
    // scrollDistance + windowHeight gives measures how far from the 'top' 
    // of the document the bottom of the viewport is, subtracting that from 
    // the offset of the div gives the difference. I used Math.Abs() because 
    // I didn't know if you wanted to know *just* how far, or if you 
    // wanted to know if it was 'above' (-difference) or 'below' (+ difference) 
    // the bottom of the viewport: 
     delta = Math.abs(divOffsetTop - (scrollDistance + windowHeight)); 

    // setting the text of the div itself, you may want to put that someplace 
    // else: 
    $('#distance').text(delta + 'px'); 
} 

// binding the function to the scroll event: 
$(window).scroll(updateScroll); 

JS Fiddle demo

参考文献: