随着用户滚动生成更多文章


Generate more articles as user scrolls

我正在建立一个网站,允许用户上传图像、gif和视频。在主页上,我想有一个人们上传的文件列表,最好是基于受欢迎程度,但我还没有走多远。当页面第一次加载时,我希望根据用户的屏幕分辨率显示一定数量的文件。在加载更多文件之前,用户可以向下滚动一点。我现在的代码是这样的:

<article class="item thumb" data-width="282">
     <h2><?php echo $file_title;?></h2>
     <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt=""></a>
</article>
<article class="item thumb" data-width="384">
     <h2><?php echo $file_title;?></h2>
     <a href="<?php echo $randomImage ?>"><img src="<?php echo $randomImage ?>" alt=""></a>
</article>

它总共做了8次。如何在用户滚动时使页面请求更多标签。。。就像Facebook在你向下滚动时加载更多内容一样?对不起,我没有好好解释。

您应该查看window.onscroll事件,在这里,当有人在您的页面上滚动窗口时,您可以挂起要调用的函数。然后,您可以决定是否需要加载更多内容。

和往常一样,MDN有一些关于这方面的文档。看看吧https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll

我在网页上使用这个方法,在那里我检查用户是否几乎滚动到了页面的底部(从底部起200px),然后我会向现有元素添加一些数据。

我有一个DIV(#main),在那里我读取最后一个条目的ID,然后我将这个ID传递到AJAX页面,并添加更多具有更高ID的条目。

$(document).ready(function() {
// Check if we have scrolled to the bottom (trigger 200px from bottom)
$(window).scroll(function() {   
  if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
    // Get the ID on the last DIV
    var lastDiv = $("#main").find("div:last");
    var lastID = lastDiv.attr("id");
    // Get the new weblog
    ajaxGet(lastID);
  }
});

// ajaxSend will send all form data for processing
// -----------------------------------------------
function ajaxGet (id) {
  $.ajax({
    url: "weblog_ajax.php",
    type: "get",
    data: { wid : id },
    async: false
  }).done(function(data) {
    $("#main").append(data); // append a new DIV
  }).fail(function(data) {
    // do something if it fails
  }).always(function(data) {
    // always do something
  });
} // function ajaxSend
});