最近在做項目的時候遇到需要做下拉刷新,就總結了一個小例子,不過其精確性還有待研究
基於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() 當前視口的高度
