복붙노트

[JQUERY] 사용자가 아래로 스크롤 경우 확인

JQUERY

사용자가 아래로 스크롤 경우 확인

해결법


  1. 1.이 같은 창에서 .scroll () 이벤트를 사용합니다 :

    이 같은 창에서 .scroll () 이벤트를 사용합니다 :

    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() == $(document).height()) {
           alert("bottom!");
       }
    });
    

    당신은 그 전체 내용 (문서)의 높이와 동일한 경우는 그래서 아래로 스크롤 얼마나 많이 보이는 창 검사의 높이를 추가,이 창 상단 스크롤합니다, 여기를 테스트 할 수 있습니다. 당신은 사용자가 하단에있는 경우 대신 확인하고 싶었다면, 그것은 다음과 같이 보일 것입니다 :

    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
           alert("near bottom!");
       }
    });
    

    당신은 조정, 여기에 해당 버전을 테스트 할 수 있습니다 100 당신이 트리거 할 바닥에서 어떤 픽셀.


  2. 2.닉 Craver의 대답은 잘 작동 $ (문서) .height의 값이 () 브라우저에 따라 다릅니다하는 문제를 아끼지.

    닉 Craver의 대답은 잘 작동 $ (문서) .height의 값이 () 브라우저에 따라 다릅니다하는 문제를 아끼지.

    이 모든 브라우저에서 작동 제임스 Padolsey에서이 기능을 사용하게하려면 :

    function getDocHeight() {
        var D = document;
        return Math.max(
            D.body.scrollHeight, D.documentElement.scrollHeight,
            D.body.offsetHeight, D.documentElement.offsetHeight,
            D.body.clientHeight, D.documentElement.clientHeight
        );
    }
    

    .height의 $ (문서) () 대신에, 마지막 코드는 그래서 :

    $(window).scroll(function() {
           if($(window).scrollTop() + $(window).height() == getDocHeight()) {
               alert("bottom!");
           }
       });
    

  3. 3.나는 정확히 확인 이유는 아직 게시되지 않은 아니지만, MDN의 설명서에 따라, 가장 간단한 방법은 기본 자바 스크립트 속성을 사용하는 것입니다 :

    나는 정확히 확인 이유는 아직 게시되지 않은 아니지만, MDN의 설명서에 따라, 가장 간단한 방법은 기본 자바 스크립트 속성을 사용하는 것입니다 :

    element.scrollHeight - element.scrollTop === element.clientHeight
    

    당신은 어떤 스크롤 요소의 하단에있을 때 true를 돌려줍니다. 그래서 단순히 자바 스크립트를 사용하여 :

    element.addEventListener('scroll', function(event)
    {
        var element = event.target;
        if (element.scrollHeight - element.scrollTop === element.clientHeight)
        {
            console.log('scrolled');
        }
    });
    

    clientHeight와 scrollTop 모두 모두 지원하는 동안 즉, (8), 더 정확히 말하면에서, 브라우저에서 폭 넓은지지를 scrollHeight. 심지어 즉 6.이 크로스 브라우저 안전합니다.


  4. 4.닉의 솔루션을 사용하고 이벤트가 발사 / 반복 경고를 받고 사람들을 위해, 당신은 경고 예를 들어 위의 코드의 라인을 추가 할 수 있습니다 :

    닉의 솔루션을 사용하고 이벤트가 발사 / 반복 경고를 받고 사람들을 위해, 당신은 경고 예를 들어 위의 코드의 라인을 추가 할 수 있습니다 :

    $(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
           $(window).unbind('scroll');
           alert("near bottom!");
       }
    });
    

    이 수단이 코드는 문서 하단의 100 픽셀 내에있어 처음 발사 것이다. 당신이 또는 당신이 닉의 코드를 사용하는지에 따라 유용하지 않을 수있다, 다시 아래 다음 백업 및 스크롤하면 그것은 반복되지 않습니다.


  5. 5.이 브라우저 성능을 향상 너무 자주, 따라서 해고되지 않도록 또한 닉 Craver에서 우수한 허용 대답에, 당신은 스크롤 이벤트를 스로틀 수 있습니다 :

    이 브라우저 성능을 향상 너무 자주, 따라서 해고되지 않도록 또한 닉 Craver에서 우수한 허용 대답에, 당신은 스크롤 이벤트를 스로틀 수 있습니다 :

    var _throttleTimer = null;
    var _throttleDelay = 100;
    var $window = $(window);
    var $document = $(document);
    
    $document.ready(function () {
    
        $window
            .off('scroll', ScrollHandler)
            .on('scroll', ScrollHandler);
    
    });
    
    function ScrollHandler(e) {
        //throttle event:
        clearTimeout(_throttleTimer);
        _throttleTimer = setTimeout(function () {
            console.log('scroll');
    
            //do work
            if ($window.scrollTop() + $window.height() > $document.height() - 100) {
                alert("near bottom!");
            }
    
        }, _throttleDelay);
    }
    

  6. 6.닉 Craver의 대답은 약간 아이폰 OS 6 사파리 모바일에서 작동하도록 수정해야하고해야합니다 :

    닉 Craver의 대답은 약간 아이폰 OS 6 사파리 모바일에서 작동하도록 수정해야하고해야합니다 :

    $(window).scroll(function() {
       if($(window).scrollTop() + window.innerHeight == $(document).height()) {
           alert("bottom!");
       }
    });
    

    주소 표시 줄이 숨겨져있는 경우 추가로 60 픽셀이 변경을 반영하지 않습니다 $ (창) .height의 ()를 사용하여 윈도우의 높이에 추가되지만 때문에 사용하는 동안 $ 변경 (창) window.innerHeight에 .height의 ()는 수행해야합니다 window.innerHeight는 않습니다.

    참고 : window.innerHeight 속성은 또한, (렌더링 될 경우) 수평 스크롤 바의 높이를 포함하는 수평 스크롤 바의 높이를 포함하지 않습니다 $ (창) .height의 ()과는 달리. 이것은 모바일 사파리에서 문제가되지 않지만 다른 브라우저 또는 모바일 사파리의 향후 버전에서 예기치 않은 동작이 발생할 수 있습니다. > =에 == 변경하면 가장 일반적인 사용의 경우에이 문제를 해결할 수 있습니다.

    여기에 window.innerHeight 속성에 대한 자세한 읽기


  7. 7.다음은 매우 간단한 방법이다

    다음은 매우 간단한 방법이다

    CONST didScrollToBottom = elm.scrollTop + elm.clientHeight == elm.scrollHeight

    elm.onscroll = function() {
        if(elm.scrollTop + elm.clientHeight == elm.scrollHeight) {
            // User has scrolled to the bottom of the element
        }
    }
    

    느릅 나무 즉 document.getElementById를에서 검색하는 요소가된다.


  8. 8.여기에 당신은 내가 위의 답변을 테스트하고 버그로 그들을 발견, 코드를 디버깅하는 데 도움이됩니다 코드의 조각이다. 나는 크롬, IE, 파이어 폭스, 아이 패드 (사파리)에서 다음을 테스트 할 수 있습니다. 나는 시험에 설치된 다른 사람이없는 ...

    여기에 당신은 내가 위의 답변을 테스트하고 버그로 그들을 발견, 코드를 디버깅하는 데 도움이됩니다 코드의 조각이다. 나는 크롬, IE, 파이어 폭스, 아이 패드 (사파리)에서 다음을 테스트 할 수 있습니다. 나는 시험에 설치된 다른 사람이없는 ...

    <script type="text/javascript">
       $(function() {
          $(window).scroll(function () {
             var docElement = $(document)[0].documentElement;
             var winElement = $(window)[0];
    
             if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
                alert('bottom');
             }
          });
       });
    </script>
    

    이 간단한 해결책이 될,하지만 난 IT 근무하는 지점에서 정지 할 수 있습니다

    당신은 여전히 ​​불량 브라우저에 문제가있는 경우, 여기 디버깅하는 데 도움이되는 몇 가지 코드는 다음과 같습니다

    <script type="text/javascript">
       $(function() {
          $(window).scroll(function () {
             var docElement = $(document)[0].documentElement;
             var details = "";
             details += '<b>Document</b><br />';
             details += 'clientHeight:' + docElement.clientHeight + '<br />';
             details += 'clientTop:' + docElement.clientTop + '<br />';
             details += 'offsetHeight:' + docElement.offsetHeight + '<br />';
             details += 'offsetParent:' + (docElement.offsetParent == null) + '<br />';
             details += 'scrollHeight:' + docElement.scrollHeight + '<br />';
             details += 'scrollTop:' + docElement.scrollTop + '<br />';
    
             var winElement = $(window)[0];
             details += '<b>Window</b><br />';
             details += 'innerHeight:' + winElement.innerHeight + '<br />';
             details += 'outerHeight:' + winElement.outerHeight + '<br />';
             details += 'pageYOffset:' + winElement.pageYOffset + '<br />';
             details += 'screenTop:' + winElement.screenTop + '<br />';
             details += 'screenY:' + winElement.screenY + '<br />';
             details += 'scrollY:' + winElement.scrollY + '<br />';
    
             details += '<b>End of page</b><br />';
             details += 'Test:' + (docElement.scrollHeight - winElement.innerHeight) + '=' + winElement.pageYOffset + '<br />';
             details += 'End of Page? ';
             if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
                 details += 'YES';
             } else {
                 details += 'NO';
             }
    
             $('#test').html(details);
          });
       });
    </script>
    <div id="test" style="position: fixed; left:0; top: 0; z-index: 9999; background-color: #FFFFFF;">
    

    나는이 사람이 약간의 시간 절약 할 수 있기를 바랍니다.


  9. 9.이 답변을 확인하시기 바랍니다

    이 답변을 확인하시기 바랍니다

     window.onscroll = function(ev) {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
           console.log("bottom");
        }
    };
    

    바닥 글 근처 또는 바닥 글에 도달 있는지 확인하기 위해 document.body.offsetHeight - 당신은 footerHeight을 수행 할 수 있습니다


  10. 10.

    var elemScrolPosition = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
    

    이 소자의 하단까지의 거리 스크롤바를 산출한다. 동일 0, 스크롤 막대가 바닥에 도달하면.


  11. 11.이것은 내 두 센트입니다 :

    이것은 내 두 센트입니다 :

    $('#container_element').scroll( function(){
            console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height())   +' _ '+ $(this)[0].scrollHeight  );
            if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
                console.log('bottom found');
            }
        });
    

  12. 12.크로스 브라우저 및 디 바운싱 (꽤 좋은 성능) 순수 JS

    크로스 브라우저 및 디 바운싱 (꽤 좋은 성능) 순수 JS

    var CheckIfScrollBottom = debouncer(function() {
        if(getDocHeight() == getScrollXY()[1] + window.innerHeight) {
           console.log('Bottom!');
        }
    },500);
    
    document.addEventListener('scroll',CheckIfScrollBottom);
    
    function debouncer(a,b,c){var d;return function(){var e=this,f=arguments,g=function(){d=null,c||a.apply(e,f)},h=c&&!d;clearTimeout(d),d=setTimeout(g,b),h&&a.apply(e,f)}}
    function getScrollXY(){var a=0,b=0;return"number"==typeof window.pageYOffset?(b=window.pageYOffset,a=window.pageXOffset):document.body&&(document.body.scrollLeft||document.body.scrollTop)?(b=document.body.scrollTop,a=document.body.scrollLeft):document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)&&(b=document.documentElement.scrollTop,a=document.documentElement.scrollLeft),[a,b]}
    function getDocHeight(){var a=document;return Math.max(a.body.scrollHeight,a.documentElement.scrollHeight,a.body.offsetHeight,a.documentElement.offsetHeight,a.body.clientHeight,a.documentElement.clientHeight)}
    

    데모 : http://jsbin.com/geherovena/edit?js,output

    PS : 디 바운서, getScrollXY 날에 의해 작성되지 getDocHeight

    나는 얼마나 작업을 보여, 내가 어떻게 할 것


  13. 13.일반 JS에서 내 솔루션 :

    일반 JS에서 내 솔루션 :

    하자 엘 = document.getElementById를 ( '엘'); el.addEventListener ( '스크롤', 기능 (E) { 경우 (this.scrollHeight - this.scrollTop - this.clientHeight <= 0) { 경고 ( '바닥'); } }); #엘자{ 폭 : 400 픽셀; 높이 : 100 픽셀; 오버플 Y : 스크롤; }

    내용
    내용
    내용
    내용
    내용
    내용
    내용
    내용
    내용
    내용
    내용


  14. 14.일치 조건이를하려고하면 하단에 스크롤

    일치 조건이를하려고하면 하단에 스크롤

    if ($(this)[0].scrollHeight - $(this).scrollTop() == 
        $(this).outerHeight()) {
    
        //code for your custom logic
    
    }
    

  15. 15.닉은 좋은 대답을하지만 당신은 스크롤 또는 사용자가 확대 창을 가지고 모든 경우에 작동하지 않습니다 동안 itsself 반복 기능을 가지고 있습니다. 난 그냥 제 1 높이를 math.round 그리고 그것은 단지로 가정 작품을 쉽게 수정 함께했다.

    닉은 좋은 대답을하지만 당신은 스크롤 또는 사용자가 확대 창을 가지고 모든 경우에 작동하지 않습니다 동안 itsself 반복 기능을 가지고 있습니다. 난 그냥 제 1 높이를 math.round 그리고 그것은 단지로 가정 작품을 쉽게 수정 함께했다.

        if (Math.round($(window).scrollTop()) + $(window).innerHeight() == $(document).height()){
        loadPagination();
        $(".go-up").css("display","block").show("slow");
    }
    

  16. 16.다음과 같은 코드를 시도 할 수 있습니다,

    다음과 같은 코드를 시도 할 수 있습니다,

    $("#dashboard-scroll").scroll(function(){
        var ele = document.getElementById('dashboard-scroll');
        if(ele.scrollHeight - ele.scrollTop === ele.clientHeight){
           console.log('at the bottom of the scroll');
        }
    });
    

  17. 17.스크롤 엘리먼트 (즉되지 창)을 검사 할 때, 정확한 결과를 제공한다 :

    스크롤 엘리먼트 (즉되지 창)을 검사 할 때, 정확한 결과를 제공한다 :

    // `element` is a native JS HTMLElement
    if ( element.scrollTop == (element.scrollHeight - element.offsetHeight) )
        // Element scrolled to bottom
    

    offsetHeight 값은 (패딩 마진 및 스크롤바 포함) 요소의 실제 높이 표시를 제공해야하고, scrollHeight 보이지 (오버플로) 영역을 포함하는 소자 전체의 높이이다.

    jQuery의 .outerHeight는 () JS의 .offsetHeight 유사한 결과를 제공한다 - 는 offsetHeight에 대한 MDN의 문서는 크로스 브라우저 지원에 대한 불분명하다. 더 많은 옵션을 포함하려면이 더 완료 :

    var offsetHeight = ( container.offsetHeight ? container.offsetHeight : $(container).outerHeight() );
    if  ( container.scrollTop == (container.scrollHeight - offsetHeight) ) {
       // scrolled to bottom
    }
    
    

  18. 18.대신 사거리 관찰자를 사용하여 스크롤 이벤트를 수신의 마지막 요소는 (평균 사용자가 아래로 스크롤 한의) 뷰포트에서 볼 수 있다면 확인을위한 저렴 하나입니다. 또한 polyfill와 IE7을 지원.

    대신 사거리 관찰자를 사용하여 스크롤 이벤트를 수신의 마지막 요소는 (평균 사용자가 아래로 스크롤 한의) 뷰포트에서 볼 수 있다면 확인을위한 저렴 하나입니다. 또한 polyfill와 IE7을 지원.

    var에 관찰자 = 새로운 IntersectionObserver (기능 (항목) { 경우 (항목 [0] .isIntersecting === TRUE) CONSOLE.LOG ( "아래로 스크롤 된"); 그밖에 을 console.log ( "안 하단에"); }, { 루트 : document.querySelector ( '# scrollContainer'), 임계 값 : 1 // 트리거 전체 요소가되었다 경우에만 볼 수 }); observer.observe (document.querySelector ( '# scrollContainer') lastElementChild.); #scrollContainer { 높이 : 100 픽셀; 오버 플로우 : 숨겨진 스크롤; }

    항목 1
    항목 2
    항목 3
    항목 4
    항목 5
    항목 6
    항목 7
    항목 8
    항목 9
    항목 10


  19. 19.나는이 같은 사용자 정의 마일스 오키프의 기능과 MEDER omuraliev을 사용할 수 있도록 이러한 모든 솔루션은 파이어 폭스와 크롬에 나를 위해하지 작업을 수행합니다 :

    나는이 같은 사용자 정의 마일스 오키프의 기능과 MEDER omuraliev을 사용할 수 있도록 이러한 모든 솔루션은 파이어 폭스와 크롬에 나를 위해하지 작업을 수행합니다 :

    function getDocHeight()
    {
        var D = document;
        return Math.max(
            D.body.scrollHeight, D.documentElement.scrollHeight,
            D.body.offsetHeight, D.documentElement.offsetHeight,
            D.body.clientHeight, D.documentElement.clientHeight
        );
    }
    
    function getWindowSize()
    {
      var myWidth = 0, myHeight = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
      }
      return [myWidth, myHeight];
    }
    
    $(window).scroll(function()
    {
        if($(window).scrollTop() + getWindowSize()[1] == getDocHeight())
        {
            alert("bottom!");
        }
    });
    

  20. 20.여기에 허용 답변으로 내 두 센트 나를 위해 일을하지 않았다입니다.

    여기에 허용 답변으로 내 두 센트 나를 위해 일을하지 않았다입니다.

    var documentAtBottom = (document.documentElement.scrollTop + window.innerHeight) >= document.documentElement.scrollHeight;
    

  21. 21.내가 JQuery와없이 approch 보여 드리죠. 단순 JS 기능 :

    내가 JQuery와없이 approch 보여 드리죠. 단순 JS 기능 :

    function isVisible(elem) {
      var coords = elem.getBoundingClientRect();
      var topVisible = coords.top > 0 && coords.top < 0;
      var bottomVisible = coords.bottom < shift && coords.bottom > 0;
      return topVisible || bottomVisible;
    }
    

    그것을 사용하는 방법을 짧은 예 :

    var img = document.getElementById("pic1");
        if (isVisible(img)) { img.style.opacity = "1.00";  }
    

  22. 22.나는 @ddanone answear 및 추가 Ajax 호출을 사용했다.

    나는 @ddanone answear 및 추가 Ajax 호출을 사용했다.

    $('#mydiv').on('scroll', function(){
      function infiniScroll(this);
    });
    
    function infiniScroll(mydiv){
    console.log($(mydiv).scrollTop()+' + '+ $(mydiv).height()+' = '+ ($(mydiv).scrollTop() + $(mydiv).height())   +' _ '+ $(mydiv)[0].scrollHeight  );
    
    if($(mydiv).scrollTop() + $(mydiv).height() == $(mydiv)[0].scrollHeight){
        console.log('bottom found');
        if(!$.active){ //if there is no ajax call active ( last ajax call waiting for results ) do again my ajax call
            myAjaxCall();
        }
    }
    

    }


  23. 23.닉의 대답의 반복되는 경고를 중지하려면

    닉의 대답의 반복되는 경고를 중지하려면

    ScrollActivate();
    
    function ScrollActivate() {
        $(window).on("scroll", function () {
            if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
                $(window).off("scroll");
                alert("near bottom!");
            }
        });
    }
    

  24. 24.구글 크롬) (당신이 $ (창)를 호출하면 페이지 .height의 전체 높이를 제공합니다

    구글 크롬) (당신이 $ (창)를 호출하면 페이지 .height의 전체 높이를 제공합니다

    대신, 윈도우의 높이를 검색 할 수 window.innerHeight를 사용합니다. 필요한 검사를해야한다 :

    if($(window).scrollTop() + window.innerHeight > $(document).height() - 50) {
        console.log("reached bottom!");
    }
    

  25. 25.분명히 무엇 나를 위해 일한 것은이 같은 '몸'이 아닌 '창'입니다 :

    분명히 무엇 나를 위해 일한 것은이 같은 '몸'이 아닌 '창'입니다 :

    $('body').scroll(function() {
    
    
     if($('body').scrollTop() + $('body').height() == $(document).height()) {
         //alert at buttom
     }
     });
    

    크로스 브라우저 호환성 사용 :

      function getheight(){
        var doc = document;
        return  Math.max(
            doc.body.scrollHeight, doc.documentElement.scrollHeight,
            doc.body.offsetHeight, doc.documentElement.offsetHeight,
            doc.body.clientHeight, doc.documentElement.clientHeight
    
            );
       }
    

    다음 대신 $ (문서) .height의 () 함수 getheight ()를 호출

    $('body').scroll(function() {
    
    
       if($('body').scrollTop() + $('body').height() == getheight()  ) {
         //alert at bottom
     }
    });
    

    근처 바닥 사용 :

    $('body').scroll(function() {
    
    
    if($('body').scrollTop() + $('body').height() > getheight() -100 ) {
        //alert near bottom
     }
     });
    

  26. 26.다른 많은 솔루션은 경고 2 회를 ​​트리거링 및 솔루션은 그래서 그것은 또한 몇 픽셀 개까지 trigerring 된 최대 이동할 때 때문에 바닥 내 사업부로 스크롤에 나를 위해 작동하지 않습니다

    다른 많은 솔루션은 경고 2 회를 ​​트리거링 및 솔루션은 그래서 그것은 또한 몇 픽셀 개까지 trigerring 된 최대 이동할 때 때문에 바닥 내 사업부로 스크롤에 나를 위해 작동하지 않습니다

            $('#your-div').on('resize scroll', function()
            {
                if ($(this).scrollTop() +
                    $(this).innerHeight() >=
                    $(this)[0].scrollHeight + 10) {
    
                    alert('reached bottom!');
                }
            });
    
  27. from https://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom by cc-by-sa and MIT license