Nice programing

무한 스크롤 jquery 플러그인

nicepro 2020. 10. 31. 10:08
반응형

무한 스크롤 jquery 플러그인


Coldfusion으로 개발중인 사이트에서 무한 스크롤을 설정하려고합니다. 저는 javascript 및 jquery를 처음 사용하므로이 모든 문제를 해결하는 데 몇 가지 문제가 있습니다. 무한 스크롤 플러그인을 사용하려면 내 사이트에 페이지 매김이 있어야합니까? 아니면이를 사용하지 않고 수행 할 수있는 방법이 있습니까?


이를 위해 무한 스크롤 플러그인이 필요하지 않습니다. 스크롤이 페이지 끝에 도달하면 감지하려면 jQuery를 사용하면됩니다.

$(window).scroll(function () { 
   if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
      //Add something at the end of the page
   }
});

JsFiddle 데모


AJAX 요청에 Hussein의 답변을 사용하고 있습니다. 10px 대신 300px에서 트리거하도록 코드를 수정했지만 스크롤 호출이 10px 범위보다 300px 범위에서 훨씬 더 자주 트리거되기 때문에 AJAX 요청이 완료되기 전에 내 추가가 증가하기 시작했습니다.

이 문제를 해결하기 위해 성공적인 AJAX로드시 뒤집히는 트리거를 추가했습니다. 내 코드는 다음과 같습니다.

var scrollLoad = true;

$(window).scroll(function () { 
  if (scrollLoad && $(window).scrollTop() >= $(document).height() - $(window).height() - 300) {
    scrollLoad = false;
    //Add something at the end of the page
  }
});

다음 내 AJAX 응답에서, 나는 설정 scrollLoadtrue.


Hussein의 작은 예제를 기반으로 jQuery 위젯을 만들었습니다. 추가 된 결과를 일시적으로 저장하기 위해 localStorage를 지원하며 추가를 자주 중지하는 일시 중지 기능이있어 계속하려면 클릭해야합니다.

시도 해봐:

http://www.hawkee.com/snippet/9445/


$(function(){ 
    $(window).scroll(function(){
           if($(document).height()<=$(window).scrollTop()+$(window).height()+100){
               alert('end of page');
           }
       });
});

누군가가 설명을 요청했기 때문에 여기에 설명이 있습니다.

여기서 $ (document) .height ()->는 전체 문서의 높이이며 대부분의 경우 현재 문서의 요소와 동일합니다.

$ (window) .height ()-> 창의 높이 (브라우저)는 브라우저에 표시되는 높이를 의미합니다.

$ (window) .scrollTop ()-> Element.scrollTop 속성은 요소의 내용이 위로 스크롤되는 픽셀 수를 가져 오거나 설정합니다. 요소의 scrollTop은 요소의 상단에서 최상위 표시 콘텐츠까지의 거리를 측정 한 것입니다. 요소 콘텐츠가 세로 스크롤 막대를 생성하지 않으면 해당 scrollTop 값의 기본값은 0입니다.

$(document).height()<=$(window).scrollTop()+$(window).height()+100

$ (window) .scrollTop ()을 $ (window) .height ()와 함께 추가하십시오. 이제 결과가 documnet 높이와 같은지 확인하십시오. 동일하다면 마지막에 도달했음을 의미합니다. 문서 하단에서 100 픽셀 이전에 확인하고 싶기 때문에 100도 추가하고 있습니다 (참고 <= 상태)

내가 틀렸다면 나를 고쳐주세요


Hussein과 Nick의 아이디어를 사용하여이 함수를 작성했지만 콜백에 promise 를 사용하고 싶었습니다 . 또한 무한 스크롤 영역이 div가 옵션 개체로 전송되는 경우 창뿐만 아니라 고정 div에 있기를 원했습니다. 아래의 두 번째 링크에 그 예가 있습니다. 이전 브라우저를 지원하려면 Q 와 같은 promise 라이브러리를 사용하는 것이 좋습니다 . cb 메서드는 약속 일 수도 있고 아닐 수도 있으며 상관없이 작동합니다.

다음과 같이 사용됩니다.

HTML

<div id="feed"></div>

js

var infScroll = infiniteScroll({
    cb: function () {
        return doSomethingPossiblyAnAJAXPromise();     
    }
});

피드를 일시적으로 중지하려면 cb 메서드에서 false를 반환 할 수 있습니다. 피드가 끝났을 때 유용합니다. infiniteScroll의 반환 된 객체 메서드 'setShouldLoad'를 호출하고 위 코드와 함께 진행하기 위해 true 및 example을 전달하여 다시 시작할 수 있습니다.

infScroll.setShouldLoad(true);

무한 스크롤 기능은 이쪽

function infiniteScroll (options) {
    // these options can be overwritten by the sent in options
    var defaultOptions = {
        binder: $(window), // parent scrollable element
        loadSpot: 300, //
        feedContainer: $("#feed"), // container
        cb: function () { },
    }

    options = $.extend(defaultOptions, options);
    options.shouldLoad = true;

    var returnedOptions = {
        setShouldLoad: function (bool) { options.shouldLoad = bool; if(bool) { scrollHandler(); } },
    };

    function scrollHandler () { 
        var scrollTop = options.binder.scrollTop();
        var height = options.binder[0].innerHeight || options.binder.height();
        if (options.shouldLoad && scrollTop >= (options.binder[0].scrollHeight || $(document).height()) - height - options.loadSpot) {
            options.shouldLoad = false;
            if(typeof options.cb === "function") {
                new Promise(function (resolve) {resolve();}).then(function() { return options.cb(); }).then(function (isNotFinished) {
                    if(typeof isNotFinished === "boolean") {
                        options.shouldLoad = isNotFinished;
                    }
                });
            }
        }
    }

    options.binder.scroll(scrollHandler);

    scrollHandler();

    return returnedOptions;

}

창을 스크롤러로 한 피드 예제

2 피드가 스크롤러 인 피드 예제


스크롤 오버플로가있는 div와 같은 스크롤 가능한 요소가 있지만 스크롤 가능한 문서 / 페이지가없는 경우이 방법을 사용할 수 있습니다.

       $(function () {
            var s = $(".your-scrollable-element");
            var list = $("#your-table-list");

            /* On element scroll */
            s.scroll(function () {
                /* The scroll top plus element height equals to table height */
                if ((s.scrollTop() + s.height()) == list.height()) {
                    /* you code */
                }
            });
        });

나는 같은 문제가 있었지만 내 필요에 적합한 플러그인을 찾지 못했습니다. 그래서 다음 코드를 작성했습니다. 이 코드는 ajax 및 페이지 매김으로 데이터를 가져 와서 요소에 템플릿을 추가합니다. 사용자가 div 하단으로 스크롤 할 때 감지하기 위해이 조건을 사용했습니다.

var t = $("#infiniteContent").offset().top;
var h = $("#infiniteContent").height();
var ws = $(window).scrollTop();
var dh = $(document).height();
var wh = $(window).height();

if (dh - (wh + ws) < dh - (h + t)) {
    //now you are at bottom of #infiniteContent element
}

$(document).ready(function(){
	$.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: 1, _limit:3 }, function (jsonre) {
        appendTemplate(jsonre,1);
    });
});

function appendTemplate(jsonre, pageNumber){
	//instead of this code you can use a templating plugin like "Mustache"
	for(var i =0; i<jsonre.length; i++){
  	$("#infiniteContent").append("<div class='item'><h2>"+jsonre[i].name+"</h2><p>"+jsonre[i].body+"</p></div>");
  }

  if (jsonre.length) {
    $("#infiniteContent").attr("data-page", parseInt(pageNumber)+1);
    $(window).on("scroll", initScroll);
    
    //scroll event will not trigger if window size is greater than or equal to document size
    var dh = $(document).height() , wh = $(window).height();
    if(wh>=dh){
    	initScroll();
    }
  }
  else {
    $("#infiniteContent").attr("data-page", "");
  }
}

function initScroll() {
    var t = $("#infiniteContent").offset().top;
    var h = $("#infiniteContent").height();
    var ws = $(window).scrollTop();
    var dh = $(document).height();
    var wh = $(window).height();

    if (dh - (wh + ws) < dh - (h + t)) {
        $(window).off('scroll');
        var p = $("#infiniteContent").attr("data-page");
        if (p) {
            $.getJSON("https://jsonplaceholder.typicode.com/comments", { _page: p, _limit:3 }, function (jsonre) {
                appendTemplate(jsonre, p);
            });
        }
    }
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div id="infiniteContent"></div>

참고 URL : https://stackoverflow.com/questions/5059526/infinite-scroll-jquery-plugin

반응형