使用方式:
new downUpData({url:"http://192.168.1.103:8080/test/data.json",distance:20,callback:function(resp,config){ var oUl = document.getElementById('ul'); for(var i=0;i<resp.data.length;i+=1){ oUl.innerHTML+= '<li>'+ resp.data[i].title +'</li>'; }}}).isBottom();

默認(rèn)滾動到底部會去請求ajax
參數(shù)說明:
url:請求的數(shù)據(jù)地址,不支持跨域(必須)
distance:距離底部多遠(yuǎn)加載(可選參數(shù))
callback:當(dāng)滾動到指定距離后請求完ajax將會觸發(fā)這個回調(diào)函數(shù),里面有兩個參數(shù),第一個為數(shù)據(jù)(以及轉(zhuǎn)成JSON對象了,用的是JSON.parse,可能低版本瀏覽器不支持這個方法),第二個參數(shù)為傳進(jìn)去的參數(shù),當(dāng)你需要重新改變請求信息的時候可以用這個,比如說你想做分頁效果,就需要改變url地址。
callback(name1,name2)
name1:data
name2:配置

源代碼:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> body,ul{ margin:0; padding:0; } </style></head><body> <ul id="ul"> </ul> <script> function downUpData(obj){ this.config = obj; }; downUpData.prototype = { // 判斷是否到達(dá)底部 isBottom:function(){ var _this = this; var scrollH = null, clientHeight = null; scrollTop = null; distance = this.config.distance||0; h = 0; function scroll(){ scrollH = document.body.scrollHeight||document.documentElement.scrollHeight; clientHeight = window.innerHeight; scrollTop = document.body.scrollTop||document.documentElement.scrollTop; h = clientHeight + scrollTop; if(h>=scrollH-distance){ _this.ajax(); } } scroll(); window.onscroll = function(){ scroll(); }; }, // 發(fā)送AJAX請求 ajax:function(){ var _this = this; var xhr = null; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("GET",this.config.url,true); xhr.onreadystatechange = function(){ if(xhr.readyState==4&&xhr.status==200){ _this.config.callback(JSON.parse(xhr.responseText),_this.config); } } xhr.send(); } }; new downUpData({url:"http://192.168.1.103:8080/test/data.json",distance:20,callback:function(resp,config){ console.log(config) var oUl = document.getElementById('ul'); for(var i=0;i<resp.data.length;i+=1){ oUl.innerHTML+= '<li>'+ resp.data[i].title +'</li>'; } }}).isBottom(); </script></body></html>以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持武林網(wǎng)!
|
新聞熱點
疑難解答