
在APP中,页面下拉刷给用户操作带来了极大的便利性。但这一效果能否在手机端的Web页中使用呢?答案是肯定的。利用HTML5中的touchstart
、touchmove
和touchend
事件,可以模拟出类似手机APP的页面下拉刷新效果。
1. HTML页面
首先,我们需要一个在页面上可触模下拉的区域,用以用户操作及JavaScript添加相关事件的监听。本站示例HTML如下:
<div id="content"> <div id="downRefresh"> <div id="down"> <p>正在下拉,释放后刷新</p> </div> <div id="refresh"> <p>正在刷新 ...</p> </div> </div> <div class="myContent"> <img src="./web/images/avatar.jpg" > </div> </div>
2. 页面样式
下面是页面的CSS代码,主要用于控制页面下拉及刷新时的提示信息区域的显示样式:
body {background-color: #9c9c9c;} #downRefresh{margin-top: 0; width: 100%;} #down, #refresh{width: 100%; height: 50px; display: none; } #down{height: 20px;} #down>p, #refresh>p{margin: 20px auto; text-align:center; font-size: 14px; color: #fff;}
3. 页面JS
有了HTML及样式,我们还需要对指定页面添加touchstart
、touchmove
和touchend
事件,以实现页面的下拉及释放刷新效果。这些事件会在以下情况下触发:
-
touchstart
事件:当手指触摸屏幕时候触发,即使已经有一个手指放在屏幕上也会触发。 -
touchmove
事件:当手指在屏幕上滑动的时会连续触发,在这个事件发生期间,调用preventDefault()
方法可以阻止滚动。 -
touchend
事件:当手指从屏幕上离开的时候触发。
在本例中,页面JS脚本及相关功能说明如下:
//第一步,下拉 function downRefreshStep1(dist){ //拉长背景以模拟拉伸效果 var down = document.getElementById("down"); var refresh = document.getElementById("refresh"); refresh.style.display = "none"; down.style.display = "block"; down.style.height = (parseInt("20px") - dist) + "px"; } //第二步,下拉完成,释放后开始刷新 function downRefreshStep2(){ var down = document.getElementById("down"); var refresh = document.getElementById("refresh"); down.style.display = "none"; down.style.height = "20px"; refresh.style.display = "block"; } //第三步,刷新完成关闭提示区 function downRefreshStep3(){ var down = document.getElementById("down"); var refresh = document.getElementById("refresh"); down.style.display = "none"; refresh.style.display = "none"; } //objId表示事件绑定对象,即:执行下拉刷新的对象 function downRefresh(objId, way){ var _content = document.getElementById(objId); var _start = 0; var _end = 0; _content.addEventListener("touchstart", touchStart, false); _content.addEventListener("touchmove", touchMove, false); _content.addEventListener("touchend", touchEnd, false); //touchstart事件监听 function touchStart(event){ var touch = event.targetTouches[0]; if(way == "x"){ _start = touch.pageX; }else{ _start = touch.pageY; } } //touchmove事件监听 function touchMove(event){ var touch = event.targetTouches[0]; if(way == "x"){ _end = (_start - touch.pageX); }else{ _end = (_start - touch.pageY); //页面下拉,进入第一步,提示:正在下拉,释放后刷新 if(_end < 0){ downRefreshStep1(_end); } } } //touchend事件监听 function touchEnd(event){ if(_end >0){ console.log("左滑或上滑"+_end); }else{ console.log("右滑或下滑"+_end); //下拉结束,进入第二步:正在刷新 ... downRefreshStep2(); //模拟刷新成功,进入第三步,关闭提示区 setTimeout(function(){ downRefreshStep3(); }, 2500); } } } //调用downRefresh方法,执行下滑刷新 downRefresh("content", "y");