1,注冊頁面滾動事件,window.onscroll = function(){ };
2,相關獲取頁面高度、滾動條位置、文檔高度的函數:
//獲取滾動條當前的位置
function getScrollTop() {
var scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
}
else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
//獲取當前可是范圍的高度
function getClientHeight() {
var clientHeight = 0;
if (document.body.clientHeight && document.documentElement.clientHeight) {
clientHeight = Math.min(document.body.clientHeight, document.documentElement.clientHeight);
}
else {
clientHeight = Math.max(document.body.clientHeight, document.documentElement.clientHeight);
}
return clientHeight;
}
//獲取文檔完整的高度
function getScrollHeight() {
return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
}
3,在html頁面底部增加代碼:
<script>
window.onscroll = function () {
if (getScrollTop() + getClientHeight() == getScrollHeight()) {
alert("到達底部");
}
}
</script>
這樣當滾動條到達頁面底部時就會觸發alert("到達底部")。下面要做的就是將觸發的功能改為ajax調用,往頁面中動態增加內容。
4,動態增加頁面元素的示例代碼:
var newnode = document.createElement("a");
newnode.setAttribute("href", "#");
newnode.innerHTML = "new item";
document.body.appendChild(newnode);
var newline = document.createElement("br");
document.body.appendChild(newline);
將這段代碼替換掉alert("到達底部");,就可以看到,當滾動條滾動到底部時,頁面底部就會增加一行”new item“,不同往下滾動,不停增加,無止盡。
5,將示例代碼修改為ajax相關代碼:
<script>
window.onscroll = function () {
if (getScrollTop() + getClientHeight() == getScrollHeight()) {
var xmlHttpReq = null;
//IE瀏覽器使用ActiveX
if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
//其它瀏覽器使用window的子對象XMLHttpRequest
else if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
if (xmlHttpReq != null) {
//設置請求(沒有真正打開),true:表示異步
xmlHttpReq.open("GET", "/ajaxtest", true);
//設置回調,當請求的狀態發生變化時,就會被調用,傳遞參數xmlHttpReq
xmlHttpReq.onreadystatechange = function () { onajaxtest(xmlHttpReq); };
//提交請求
xmlHttpReq.send(null);
}
}
}
function onajaxtest(req) {
var newnode = document.createElement("a");
newnode.setAttribute("href", "#");
newnode.innerHTML = req.readyState + " " + req.status + " " + req.responseText;
document.body.appendChild(newnode);
var newline = document.createElement("br");
document.body.appendChild(newline);
}
</script>
當滾動條到頁面底部之后,就會增加以下節點,如下:
2 200
3 200 ajax ok
4 200 ajax ok
這里2、3、4,就是請求的狀態readyState,200就是http的回應狀態status,ajax ok是/ajaxtext應用返回的文本,具體查看以下參考資料。
按照XMLHttpRequest的的文檔說明,應該能夠打印出:
0 200
1 200
2 200
3 200 ajax ok
4 200 ajax ok
但是我這里沒有打印出0和1這兩個狀態,這是為什么呢,路過的高手方便吱一聲嗎?