原生JS下拉加载插件分享。

无聊写了一个JS下拉加载插件,有需要的可以下载。

// 使用
// new ManDownLoad("#ul","json/load.json",function(data,obj){
// var str = "";
// data.data.forEach(function(item,index){
// str += "<li>" + item.title + "</li>";
// });
// return str;
// },{
// type:"POST",
// data:{
// "hello":"world",
// "fa":"bbb"
// }
// });
;function ManDownLoad(element,url,callback,obj){
this.element = element;
if((typeof element)==="string"){
this.element = document.querySelector(element);
}
this.url = url;
this.callback = callback;
var options = {
type:"GET",
distance:0,
dataType:"json",
data:{}
};
this.config = this.extend(options,obj);
this.init();
};
ManDownLoad.prototype = {
init:function(){
var _this = this;
this.isBottom();
window.addEventListener("scroll",this.isBottom);
},
// 判断是否到达底部
isBottom:function(){
var _this = this;
var scrollH = null,
clientHeight = null,
scrollTop = null,
h = 0; scrollH = document.body.scrollHeight||document.documentElement.scrollHeight;
clientHeight = window.innerHeight;
scrollTop = document.body.scrollTop||document.documentElement.scrollTop;
h = clientHeight + scrollTop;
if(h>=scrollH-_this.config.distance){
_this.ajax();
}
},
// 发送AJAX请求
ajax:function(){
var _this = this;
var xhr = new XMLHttpRequest();
var data = null; xhr.open(this.config.type,this.url,true);
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
if(_this.config.dataType==="json"){
data = _this.callback(JSON.parse(xhr.responseText),_this);
}else{
data = _this.callback(xhr.responseText,_this);
}
if(data===false){
window.removeEventListener("scroll",_this.isBottom);
}
_this.addHTML(data,function(){
_this.isBottom();
});
}
}
xhr.send(_this.toFormStr(_this.config.data));
},
addHTML:function(data,callback){
if(!data)return;
if((typeof data)==="string"){
this.element.innerHTML += data;
}else{
this.element.appendChild(data);
}
callback&&callback();
},
toFormStr:function(obj){
var str = "";
for(var k in obj){
str += k + "=" + obj[k] + "&";
}
return str.slice(0,-1);
},
extend:function(obj,obj2){
if(!obj)return obj2;
for(var k in obj2){
obj[k] = obj2[k];
}
return obj;
}
};
上一篇:H3CNE实验:Comware基本命令操作


下一篇:ansible写一个简单的playbook