原生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;
  }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值