【问题标题】:Generate more articles as user scrolls随着用户滚动生成更多文章
【发布时间】:2013-07-17 02:41:51
【问题描述】:

我正在建立一个允许用户上传图片、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 在您向下滚动时加载更多内容一样?抱歉,如果我没有很好地解释这一点。

【问题讨论】:

标签: php ajax html loading


【解决方案1】:

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

与往常一样,MDN 对此有一些文档。看看这个 https://developer.mozilla.org/en-US/docs/Web/API/window.onscroll

【讨论】:

    【解决方案2】:

    我在我的网页上使用这种方法,我检查用户是否几乎滚动到页面底部(距离底部 200 像素),然后我将向现有元素添加一些数据。

    我有一个 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
    
    });
    

    【讨论】:

    • 所以,我只想加载更多带有随机图像的块。我将如何编写将进入 "url: *" 引用的页面中的代码我是否只是将当前加载随机文件的代码放入主页的文章标签中?或者ajax php文件需要采用什么特殊格式?
    猜你喜欢
    • 2013-12-23
    • 2015-02-16
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多