1. 페이지 스크롤 이벤트 등록, Window.onscroll = function () {};
2. 관련 기능 페이지 높이, 스크롤 막대 위치 및 문서 높이를 얻기위한 관련 기능 :
코드 사본은 다음과 같습니다.
// 스크롤 바의 현재 위치를 가져옵니다
함수 getscrolltop () {
var scrolltop = 0;
if (document.documentElement && document.documentElement.scrolltop) {
scrolltop = document.documentElement.scrolltop;
}
else if (document.body) {
scrolltop = document.body.scrolltop;
}
반환 스크롤 탑;
}
// 현재 범위 높이를 얻습니다
함수 getClientHeight () {
var clientHeight = 0;
if (document.body.clientheight && document.documentElement.clientHeight) {
clientHeight = math.min (document.body.clientHeight, document.documentElement.clientHeight);
}
또 다른 {
ClientHeight = Math.Max (Document.Body.ClientHeight, Document.DocumentElement.ClientHeight);
}
ClientHeight를 반환합니다.
}
// 문서의 전체 높이를 가져옵니다
함수 getScrollHeight () {
return math.max (document.body.scrollheight, document.documentElement.scrollheight);
}
3. HTML 페이지 하단에 코드 추가 :
코드 사본은 다음과 같습니다.
<cript>
window.onscroll = function () {
if (getScrollTop () + getClientHeight () == getScrollHeight ()) {
경고 ( "하단 도달");
}
}
</스크립트>
스크롤 막대가 페이지 하단에 도달하면 경고 ( "하단에 도달")를 트리거합니다. 다음에해야 할 일은 트리거 된 기능을 Ajax 호출로 변경하고 페이지에 컨텐츠를 동적으로 추가하는 것입니다.
4. 동적으로 페이지 요소를 추가하기위한 코드 예제 :
코드 사본은 다음과 같습니다.
var newnode = document.createElement ( "a");
newNode.setAttribute ( "href", "#");
newnode.innerhtml = "새 항목";
document.body.appendchild (Newnode);
var newline = document.createElement ( "br");
document.body.appendChild (Newline);
이 코드를 Alert로 바꾸십시오 ( "하단 도달"); 그리고 스크롤 바가 바닥에 스크롤되면 페이지 하단에 "새 항목"이 추가 될 것임을 알 수 있습니다. 다른 스크롤 아래로, 끝없이 지속적으로 증가합니다.
5. 샘플 코드를 Ajax 관련 코드로 수정합니다.
코드 사본은 다음과 같습니다.
<cript>
window.onscroll = function () {
if (getScrollTop () + getClientHeight () == getScrollHeight ()) {
var xmlhttpreq = null;
// 즉, 브라우저는 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);
}
}
}
기능 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);
}
</스크립트>
스크롤 막대가 페이지 하단에 도달하면 다음과 같이 다음 노드가 추가됩니다.
2 200
3 200 Ajax OK
4 200 Ajax OK
여기서 2, 3 및 4는 요청 된 상태 ReadyState, 200은 HTTP의 응답 상태이며 Ajax OK는 /ajaxtext 응용 프로그램에서 반환 한 텍스트입니다. 자세한 내용은 다음 참조 자료를 확인하십시오.
xmlhttprequest의 문서 지침에 따르면 인쇄 할 수 있어야합니다.
0 200
1 200
2 200
3 200 Ajax OK
4 200 Ajax OK
그러나 나는 0과 1의 두 상태를 인쇄하지 않았다. 왜 이런 일입니까? 통행인이 삐걱 거리는 것이 편리합니까?