天天看點

無限滾動插件Infinite Scroll

最近一個項目需要用到無限滾動,調查了很多最後用了Infinite Scroll這個插件。

優點

①ajax的函數是内部已經封裝好,所有不需要單獨的調用。

②背景傳回的形式既可以是靜态html形式也可以說json  。

使用infinite-scroll

安裝引用就不寫了,可以去官網自己看。

1.主的HTML部分

<div class="container"> 

</div>
<div class="page-load-status">
    <div class="loader-ellips infinite-scroll-request"><!-- 在加載時顯示 -->
        <span class="loader-ellips__dot"></span>
        <span class="loader-ellips__dot"></span>
        <span class="loader-ellips__dot"></span>
        <span class="loader-ellips__dot"></span>
    </div>
    <p class="infinite-scroll-last">End of content</p><!-- 最後一頁加載完了顯示 -->
    <p class="infinite-scroll-error">No more pages to load</p><!-- 加載錯誤的時候顯示 -->
</div>
           

2.主的css部分

body {
  font-family: sans-serif;
  line-height: 1.4;
  font-size: 18px;
  margin: 0 auto;
}

.page-load-status {
  display: none;
  padding-top: 20px;
  border-top: 1px solid #DDD;
  text-align: center;
  color: #777;
}
.loader-ellips {
  font-size: 20px; /* change size here */
  position: relative;
  width: 4em;
  height: 1em;
  margin: 10px auto;
}

.loader-ellips__dot {
  display: block;
  width: 1em;
  height: 1em;
  border-radius: 0.5em;
  background: #555; /* change color here */
  position: absolute;
  animation-duration: 0.5s;
  animation-timing-function: ease;
  animation-iteration-count: infinite;
}

.loader-ellips__dot:nth-child(1),
.loader-ellips__dot:nth-child(2) {
  left: 0;
}
.loader-ellips__dot:nth-child(3) { left: 1.5em; }
.loader-ellips__dot:nth-child(4) { left: 3em; }

@keyframes reveal {
  from { transform: scale(0.001); }
  to { transform: scale(1); }
}

@keyframes slide {
  to { transform: translateX(1.5em) }
}

.loader-ellips__dot:nth-child(1) {
  animation-name: reveal;
}

.loader-ellips__dot:nth-child(2),
.loader-ellips__dot:nth-child(3) {
  animation-name: slide;
}

.loader-ellips__dot:nth-child(4) {
  animation-name: reveal;
  animation-direction: reverse;
}
           

3.頁的HTML部分

<div class="container">
    <article class="post">
        <!-- 内容 --> 
    </article>
</div>
           

4.主的js部分,也是最主要的部分

var infScroll = new infinitescroll('.container', {
    path: function () { 
        var maxPage = 10; //最大頁數
        if (this.loadCount < maxPage) {
            var pageNumber = this.loadCount + 1;
            return '/demo/image?page=' + pageNumber;
        }
    },
    append: '.post', // 把頁面顯示出來的方式,預設是false
//  responseType: 'text', // 設定頁面請求傳回的響應類型 text時是json
    prefill: true, //預填充 ,加上後append屬性必須。
    status: '.page-load-status',
    hideNav: '.pagination',
    history: false, //更改浏覽器曆史記錄和URL。
    scrollThreshold: 100//設定滾動條與滾動區域之間的距離,預設是400
})
           

5.幾個常用的事件

// 頁面請求加載下一頁時觸發。
infScroll.on('request', function (path) {

})

// 頁面附加到容器前觸發。
infScroll.on('load', function (response, path) {

});

// 頁面附加到容器後觸發。 append: '.post'有效。
infScroll.on('append', function (response, path, items) {

});
           

6.最後

其他的功能還有一些,主要還是需要去看官方文檔。