向下滚动jquery时如何获取浏览器屏幕窗口的位置

时间:2016-07-28 17:46:02

标签: javascript jquery html css

当用户滚动到网站底部时,脚本将从数据库查询数据 但我希望在箭头栏之前的查询数据等于浏览器的底部。 当用户滚动到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);
});

enter image description here

1 个答案:

答案 0 :(得分:1)

这应该有效。如果你想要"无限滚动"效果,您必须重置triggerFlag,并重新更新docHeighttriggerHeight值,以便在您使用新值更新DOM时新文档高度来自ajax请求。



$(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>
&#13;
&#13;
&#13;