如何在div滚动结束时触发功能

时间:2017-11-24 09:36:19

标签: javascript jquery

我正在使用jquery infinity分页。我有div在哪个产品动态调用让我们说

<div id="product_list">
<?php include ('products.php'); ?>
</div>

现在如何在用户到达最后一个产品时触发loadMoreData()功能我尝试此功能但在页面末尾工作。

$(window).scroll(function() {

if($(window).scrollTop() + $(window).height() >= $(document).height()) {
     var last_id = $(".post-id:last").attr("id");
        alert(last_id);
        loadMoreData(last_id);
      }
});
 function loadMoreData(last_id){
  $.ajax(
        {
            url: 'loadMoreData.php?last_id=' + last_id,
            type: "get",
            beforeSend: function()
            {
                $('.ajax-load').show();
            }
        })
        .done(function(data)
        {
            $('.ajax-load').hide();
            $("#post-data").html(data);
        })
        .fail(function(jqXHR, ajaxOptions, thrownError)
        {
              alert('server not responding...');
        });
}

1 个答案:

答案 0 :(得分:1)

使用此示例代码,然后根据您的需要修改滚动功能

<!DOCTYPE html>
<div id="product_list">
	<div style="background-color: green; height: 400px;"></div>
	<div style="background-color: blue; height: 400px;"></div>
	<div style="background-color: green; height: 400px;"></div>
	<div style="background-color: blue; height: 400px;"></div>
</div>

<div style="background-color: green; height: 100px;"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $("#product_list").height()) {

        alert("hi");
}
});
</script>

此代码计算窗口高度并将其与div (product_list)高度进行比较。如果滚动到div的末尾,则会弹出alert