一个index.html页面,一个scroll.js即可实现简单的功能
index.html页面代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>滚动条测试</title>
<style>
.parent_div {
width: auto;
height: auto
}
</style>
</head>
<body id="myScrollspy" >
<div class="parent_div">
<ul id="my_list">
<li>滑动鼠标滚轮列出所有id</li>
</ul>
</div>
<script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script src="scroll.js"></script>
<script src="jquery.nicescroll.js"></script>
</body>
</html>
scroll.js代码如下:
(function ($) {
var pos = 0;
var LIST_ITEM_SIZE = 56;
//滚动条距底部的距离
var BOTTOM_OFFSET = 0;
var page = 1
var total = 10
var display = 0
createListItems();
$(document).ready(function () {
/* 美化滚动条 */
$('body').niceScroll({
cursorcolor: '#6E6E7D', ////#6E6E7D 光标颜色
touchbehavior: false, //使光标拖动滚动像在台式电脑触摸设备
cursoropacitymin: 0,
cursoropacitymax: 1, //改变不透明度非常光标处于活动状态(scrollabar“可见”状态),范围从1到0
cursorwidth: '5px', ////像素光标的宽度
cursorborder: '1px solid #424242', // 游标边框css定义
cursorborderradius: '5px', //以像素为光标边界半径
autohidemode: true //是否隐藏滚动条
})
// 实现滚动加载
$(window).scroll(function () {
var $currentWindow = $(window);
//当前窗口的高度
var windowHeight = $currentWindow.height();
console.log("current widow height is " + windowHeight);
//当前滚动条从上往下滚动的距离
var scrollTop = $currentWindow.scrollTop();
console.log("current scrollOffset is " + scrollTop);
//当前文档的高度
var docHeight = $(document).height();
console.log("current docHeight is " + docHeight);
//当 滚动条距底部的距离 + 滚动条滚动的距离 >= 文档的高度 - 窗口的高度
//换句话说:(滚动条滚动的距离 + 窗口的高度 = 文档的高度) 这个是基本的公式
if ((BOTTOM_OFFSET + scrollTop) >= docHeight - windowHeight) {
createListItems();
}
});
});
function createListItems() {
var mydocument = document;
var mylist = mydocument.getElementById("my_list");
var docFragments = mydocument.createDocumentFragment();
var result =getPageInfo({type:'emergenciesList',page:page,size:50},function(data){
display += 50
console.log(display)
if(data.success && data.result){
total = data.result.total
page +=1
var datas = data.result.data
for (var i = datas.length - 1; i >= 0; i--) {
var liItem = mydocument.createElement("li");
liItem.innerHTML = "id为" + datas[i].id;
docFragments.appendChild(liItem);
};
} else {
for (var i = pos; i < pos + LIST_ITEM_SIZE; ++i) {
var liItem = mydocument.createElement("li");
liItem.innerHTML = "id为 " + i;
docFragments.appendChild(liItem);
}
pos += LIST_ITEM_SIZE;
}
mylist.appendChild(docFragments);
})
}
/*
* 异步加载调用后台
*/
function getPageInfo(data,callbackfun){
try {
$.ajax({
type: 'post',
url: 'http://localhost:8008/api/data/getPage' + '?temp=' + Math.random(),
async: true,
cache: false,
contentType: 'application/json',
data: typeof data === 'string' ? data : JSON.stringify(data),
dataType: 'JSON',
success: function (msg) {
callbackfun(msg)
},
error: function (msg) {
callbackfun({success: false, msg: '错误!'})
}
})
}catch (e) {
console.log('错误提示', e.message)
callbackfun({success: false, msg: '错误!'})
}
}
})(jQuery);