1。ページスクロールイベント、window.onscroll = function(){}を登録します。
2。ページの高さ、スクロールバーの位置、ドキュメントの高さを取得するための関連機能:
コードコピーは次のとおりです。
// Scrollbarの現在の位置を取得します
function getscrolltop(){
var scrolltop = 0;
if(document.documentelement && document.documentelement.scrolltop){
scrolltop = document.documentelement.scrolltop;
}
else if(document.body){
scrolltop = document.body.scrolltop;
}
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を返します。
}
//ドキュメントの完全な高さを取得します
function getscrollheight(){
return math.max(document.body.scrollheight、document.documentelement.scrollheight);
}
3. HTMLページの下部にコードを追加します。
コードコピーは次のとおりです。
<スクリプト>
window.onscroll = function(){
if(getscrolltop() + getClientHeight()== getScrollheight()){
アラート( "bottom the Bottom");
}
}
</script>
これにより、スクロールバーがページの下部に到達したときにアラート(「下部に到達する」)がトリガーされます。次に行う必要があるのは、トリガーされた関数を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);
このコードをアラートに置き換えます( "bottom the Bottom");また、スクロールバーが下部にスクロールすると、ページの下部に「新しいアイテム」が追加されることがわかります。異なるスクロールダウン、継続的に増加し、無限に増加します。
5.サンプルコードをAJAX関連コードに変更します。
コードコピーは次のとおりです。
<スクリプト>
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の応答ステータス、Ajax OKは /ajaxtextアプリケーションによって返されるテキストです。詳細については、次の参考資料を確認してください。
xmlhttprequestのドキュメントの指示によると、印刷できるはずです。
0 200
1 200
2 200
3 200 Ajax OK
4 200 Ajax OK
しかし、私は0と1の2つの状態を印刷しませんでした。なぜこれはなぜですか?通行人がきしむのを作るのは便利ですか?