您的位置:首页 > 其它

使用iscroll上拉刷新和下拉刷新

2018-03-03 16:04 120 查看
上拉或者下拉刷新的需求在移动端是非常常见的需求,大部分情况下,实现这个效果都使用网上现有的解决方案,例如有人使用
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();
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iscroll