上拉或者下拉刷新的需求在移動端是非常常見的需求,大部分情況下,實現這個效果都使用網上現有的解決方案,例如有人使用swiper
這個插件, 也有人使用iScroll
這個滾動插件。本文的示例是利用iscroll實現的下拉刷新效果。
iScroll簡介
iScrool
是目前最成熟的自定義滾動解決方案之一,在移動端和PC有很好的兼容性。iScroll官方提供了5個不同的版本:
- iscroll.js 通用版 包含了大部分公共特性
- iscroll-lite.js 縮減版 削減了一些功能特性,例如:滾動條,鼠標滾輪等等
- iscroll-probe.js 探索版 此版本可以滿足你獲取滾動條位置的需求。
- iscroll-zoom.js 滾動縮放版
- iscroll-infinite.js 無限制版
根據不同的需求,選擇相應的版本,當前的示例中,我們選擇的是iscroll-probe.js
版。
Gitbook地址:iScroll API 中文版
詳細使用
代碼思路則是:利用監聽滾動條的scroll
事件,判斷下拉或者上拉的距離,做上觸發距離標記,當scrollEnd
事件觸發時,執行數據加載。讓我們看核心部分代碼:
HTML代碼結構
<div id="MyScroller" class="main"> <div class="warpper"> <div id="PullDown" class="scroller-pullDown" style="display: none;"> <img style="width: 20px; height: 20px;" src="rolling.svg" /> <span id="pullDown-msg" class="pull-down-msg">下拉刷新</span> </div> <ul id="Content" class="dropdown-list"> </ul> <div id="PullUp" class="scroller-pullUp" style="display: none;"> <img style="width: 20px; height: 20px;" src="rolling.svg" /> <span id="pullUp-msg" class="pull-up-msg">上拉刷新</span> </div> </div> </div>
CSS樣式
.scroller { position: relative; width: 100%; height: 100%; } .scroller .warpper { position: absolute; width: 100%; } .scroller-pullDown, .scroller-pullUp { width: 100%; height: 30px; padding: 10px 0; text-align: center; } .dropdown-list { padding: 0; margin: 0; } .dropdown-list li { width: 100%; background: #ddd; line-height: 45px; text-align: center; color: #FFF; border-bottom: 1px solid #FFF; }
javascript
var pullDown = document.querySelector("#PullDown"), pullUp = document.querySelector("#PullUp"), isPulled = false; // 拉動標記 var myScroll = new IScroll('#MyScroller', { probeType: 3, mouseWheel: true, scrollbars: true, preventDefault: false, fadeScrollbars: true }); myScroll.on('scroll', function() { var height = this.y, bottomHeight = this.maxScrollY - height; // 控制下拉顯示 if (height >= 60) { pullDown.style.display = "block"; isPulled = true; return; } else if (height < 60 && height >= 0) { pullDown.style.display = "none"; return; } // 控制上拉顯示 if (bottomHeight >= 60) { pullUp.style.display = "block"; isPulled = true; return; } else if (bottomHeight < 60 && bottomHeight >= 0) { pullUp.style.display = "none"; return; } }) myScroll.on('scrollEnd', function() { // 滾動結束 if (isPulled) { // 如果達到觸發條件,則執行加載 isPulled = false; appendContent(getContents()); myScroll.refresh(); } });
完整的demo請看:
http://wewoor.github.io/js-lab/iscroll-pulldown-load/index.html