簡體   English   中英

向下滾動jQuery時如何獲取瀏覽器屏幕窗口的位置

[英]How to get the position of screen window of browser when scroll down jquery

這是腳本,當用戶滾動到網站底部時腳本將從數據庫查詢數據,但是我想在箭頭欄等於瀏覽器底部之前查詢數據。 我想查詢數據或在用戶滾動到2/3或接近瀏覽器底部時加載ajax,而不是直到瀏覽器底部

$(document).ready(function () {
    var lastScrollTop = 0;

    document.addEventListener("scroll", function() { // or window.addEventListener("scroll"....

        var st = window.pageYOffset || document.documentElement.scrollTop;

        if (st > lastScrollTop) {

            if ($(window).scrollTop() + $(window).height() === $(document).height()) {

                $.ajax({
                    url:'products/scroll',
                    method:'get',
                    dataType:'html',
                    data:{},
                    success : function (data, status) {
                        console.log(data);
                        $(data).appendTo('.load-more-block')
                    }
                })
            }
        }

        lastScrollTop = st;
    }, false);
});

在此處輸入圖片說明

這應該工作。 如果要獲得“無限滾動”效果,每當您的DOM用ajax請求中的新值更新時,就必須重置triggerFlag ,並將docHeighttriggerHeight值重新更新為新的文檔高度。

 $(document).ready(function(){ var docHeight = $(document).height(); var triggerHeight = docHeight*0.6667; $("#docHeight").text(docHeight); //Ignore $("#triggerHeight").text(triggerHeight); //Ignore var triggerFlag = false; $(window).scroll(function(){ $("#height").text($(this).scrollTop()); //Ignore if (!triggerFlag && $(this).scrollTop() > triggerHeight){ //Execute code here triggerFlag = true; $("#status").text("Executed at " + new Date()); } }); }); 
 html{ height: 6000px; } p{ position: fixed; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-2.2.4.js"></script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <p> Current Height: <span id='height'>0</span><br> Window Height: <span id='docHeight'>0</span><br> Trigger Height: <span id='triggerHeight'>0</span><br> Status: <span id='status'>false</span> </p> </body> </html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM