2014-10-28 4 views
0

jQuery를 사용하면 div 위쪽과 내 뷰포트 하단 사이의 높이를 어떻게 찾을 수 있습니까?div 위쪽과 창의 아래쪽 사이의 높이 찾기

제 코드에서는 스크롤하는 동안 바닥 글의 상단과 창 하단 사이의 거리를 적극적으로 찾아야합니다.

어떻게하면 좋을까요?

+0

[this] (http://stackoverflow.com/questions/9880472/determine-distance-from-the-top-of-a-div-to-top-of-window-with-javascript) 그래서 대답을 받아 들였고, 도움이되기를 바랍니다. –

답변

2

한 간단한 방법 :

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.

참고 :

관련 문제