最近在做项目的时候遇到需要做下拉刷新,就总结了一个小例子,不过其精确性还有待研究
基于jQuery的scroll事件来实现滚动条到达最低部,进行刷新
主要原理是当滚动条卷起的高度加上屏幕或者设备的高度的和大于等于文档的高度的时候进行刷新
在例子只是做了一个简单的虚假刷新,引用jQuery的.clone()和.appendTo()方法。
下面给出代码
<pre name="code" class="html"><!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>下拉刷新</title>
<script src="jquery-1.11.3.js"></script>
<style>
*{ margin: 0;padding: 0;}
</style>
</head>
<body>
<div id="container">
<div style="width:100%;height:300px;background:#f00">111111111</div>
<div style="width:100%;height:300px;background:#0f0">222222222</div>
<div style="width:100%;height:300px;background:#00f">333333333</div>
</div>
<div id="jiazai" style="position:fixed;bottom:0;left:0;width:100%;line-height:20px;font-size:16px;color:#fff;text-align:center;display:none;">正在加载</div>
<script>
//滚动到页面底部时,自动加载更多
$(window).scroll(function(){
var scrollh = $(document).height();
var scrollTop=Math.max(document.documentElement.scrollTop||document.body.scrollTop);
if((scrollTop + $(window).height()) >= scrollh){
$("#jiazai").show();
var interval = setTimeout(function(){
$("#jiazai").hide();
},1000);
var inter = setTimeout(function(){
$("#container div").first().clone().appendTo($("#container"));
},1000);
}
});
</script>
</body>
</html>
$(document).height()指的是文档的总高度
<pre name="code" class="html">Math.max(document.documentElement.scrollTop||document.body.scrollTop)滚动条卷起来的高度
<pre name="code" class="html">$(window).height() 当前视口的高度