【问题标题】:Infinite Scroll with history.pushState使用 history.pushState 进行无限滚动
【发布时间】:2016-04-02 11:25:23
【问题描述】:

我遇到了另一个 jQuery 问题。好吧,我从我的代码开始在这里理解我的问题:

<script type="text/javascript">
jQuery(document).ready(function() {

  var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
  var idp;

  $(window).scroll(function(e){
    if($(window).scrollTop() + $(window).height() >= $(document).height()) {
      current=current+1;
      if(current<=1)
      {
        idp = '';
      }
      else
      {
        idp = '?page='+current;
      }
      loadMoreContent(idp);

      history.pushState("state", "title: "+current, "index.php"+idp);
            e.preventDefault();
    }
    if($(window).scrollTop() == 0) {
      current=((current-1)<=0) ? 1 :  current-1;
      if(current<=1)
      {
        idp = '';
      }
      else
      {
        idp = '?page='+current;
      }

      loadMoreContent(idp);

      history.pushState("state", "title: "+current, "index.php"+idp);
            e.preventDefault();

    }
  });

  window.onpopstate = function(event) {
      if(current<=1)
      {
        idp = '';
      }
      else
      {
        idp = '?page='+current;
      }
        loadMoreContent(idp);
        history.pushState("state", "title: "+current, "index.php"+idp);
      };

  function loadMoreContent(position) {
      $('#loader').fadeIn('slow', function() {
        $.get("index.php"+position+" #annonceis", function(data){
          var dato = $(data).find("#annonceis");
          $("#annonceis").html(dato);
          $('#loader').fadeOut('slow', function() {
            $(window).scrollTop(60);
          });
        });
      });
  }
});
</script>

我的问题是基于无限滚动,但我使用 html() 函数替换了名为 annonceis 的 div 中的内容,而不是“追加”。

这个想法是,当我滚动到页面底部时,我会得到名为 index.php?page=1 2 3 的新页面的内容。然后用我的新内容替换 de div annonceis 中的旧内容使用 jQuery 获取,但是当我滚动到底部时,当当前页面为 index.php?page=2 时,我获取下一页的内容,通常当我滚动到底部时,我必须获取 index.php?page=3 的内容,但是在这里我得到 index.php?page=3 的内容并立即 index.php?page=4 所以页面显示 index.php?page=4.

主要思想是滚动到底部并获取下一页的内容而不是分页,但它必须注意用于 SEO 目的的 history.pushState 和 Google 建议参见 http://scrollsample.appspot.com/itemshttps://googlewebmastercentral.blogspot.com/2014/02/infinite-scroll-search-friendly.html

非常感谢您。

【问题讨论】:

    标签: php jquery infinite-scroll


    【解决方案1】:

    嘿兄弟@LionelRitchietheManatee Finnaly 我已经解决了这个问题,这是我使用的代码。

    <script type="text/javascript">
    jQuery(document).ready(function() {
      
      var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
      var idp;
      var loaded = true;
    
      $(window).scroll(function(e){
        if(($(window).scrollTop() + $(window).height() == $(document).height())&&(loaded)) {
          loaded = !loaded;
          current=current+1;
          if(current<=1)
          {
            idp = '';
          }
          else
          {
            idp = '?page='+current;
          }
          loadMoreContent(idp);
    
          history.pushState("state", "title: "+current, "index.php"+idp);
                e.preventDefault();
        }
        if($(window).scrollTop() == 0) {
          loaded = !loaded;
          current=((current-1)<=0) ? 1 :  current-1;
          if(current<=1)
          {
            idp = '';
          }
          else
          {
            idp = '?page='+current;
          }
          
          loadMoreContent(idp);
    
          history.pushState("state", "title: "+current, "index.php"+idp);
                e.preventDefault();
    
        }
      });
    
      
    
      window.onpopstate = function(event) {
          if(current<=1)
          {
            idp = '';
          }
          else
          {
            idp = '?page='+current;
          }
            loadMoreContent(idp);
            history.pushState("state", "title: "+current, "index.php"+idp);
          };
    
      function loadMoreContent(position) {
          $('#loader').fadeIn('slow', function() {
            $.get("index.php"+position+" #annonceis", function(data){ 
              var dato = $(data).find("#annonceis");
              $("#annonceis").html(dato);
              $('#loader').fadeOut('slow', function() {
                loaded = !loaded;
                $(window).scrollTop(60);
              }); 
            });
          });
      }
    });
    </script>

    我添加了一个名为“loaded”的新变量,初始值为 TRUE,它会在加载内容时更新为 FALSE 状态,并在我们开始滚动时更新为 TRUE 状态。

    我很原始,因为解决方案不像你那样干净,但它解决了我的问题。

    谢谢你的帮助,你是BOSS。

    【讨论】:

      【解决方案2】:

      所以,您真正追求的是分页与无限滚动的结合。所提供的示例正在使用.pushState() 跟踪用户使用页面航点滚动。注意,一旦页面 X 到达页面中心点,.pushState() 就会被触发。

      其次,如果您查看示例的任何页面的源代码,您会发现它只会呈现选定的页面,然后使用.scroll 上的侦听器将根据需要附加或前置内容。

      所以,从本质上讲,这实际上只是简单的分页。无限滚动的感觉被简单地添加到用户体验的顶部。执行此操作的基本概述如下所示:

      模型或控制器

      运行实际查询的 PHP 文件或其他文件 - 基于类以方便使用。该类将包含一个函数,用于根据请求页面获取一组帖子。 JavaScript 将处理所有其他事情。

      <?php
      
      Class InfiniteScroller {
      
          // Set some Public Vars
          public $posts_per_page = 5;
          public $page;
      
          /**
          * __construct function to grap our AJAX _POST data
          */
          public function __construct() {
      
              $this->page = ( isset($_POST['page']) ? $_POST['page'] : 1 );
      
          }
      
      
          /**
          * Call this function with your AJAX, providing what page you want
          */
          public function getPosts() {
      
              // Calculate our offset
              $offset = ($this->posts_per_page * $this->page) - $this->posts_per_page;
      
              // Set up our Database call
              $SQL = "SELECT * FROM my_post_table ORDER BY post_date ASC LIMIT " . $offset . ", " . $this->posts_per_page;
      
              // Run Your query, format and return data
              // echo $my_formatted_query_return;
      
          }
      
      }
      
      ?>
      

      AJAX 调用

      接下来您需要处理的是前端和 JavaScript,因此您的 AJAX 调用可以放在一个简单地调用上述方法并接受页面参数的函数中。

      <script type="text/javascript">
      
      function getPageResults( page = 1, arrange = 'next' ) {
          $.ajax({
              url: url;
              type: "POST",
              data: "?page=" + page,
              success: function(html) {
                  /* print your info */
                  if( arrange == 'prev' ) {
                      $( '#myResults' ).prepend(html);
                  else if( arrange == 'next' ) {
                      $( '#myResults' ).append(html);
                  }
              },
              error: function(e) {
                  /* handle your error */
              }
      
          });
      }
      
      </script>
      

      HTML 视图

      您的 HTML 将是相当基本的,只是一个存放显示结果和一些创意触发器的地方。

      <html>
      <head>
      </head>
      <body>
      
          <div class="loadPrev"></div>
      
          <div id="myResults">
              <!-- Your Results will show up here -->
          </div>
      
          <div class="loadNext"></div>
      
      </body>
      </html>
      

      加载您想要的页面

      总而言之,您的最后一个难题是根据 URL 中的查询字符串加载请求的页面。如果不存在查询字符串,则需要第 1 页。否则,加载请求的页面。

      <script type="text/javascript">
      
      $( document ).ready(function() {
      
          var page = <?php echo ( isset($_GET['page'] ? $_GET['page'] : 1) ?>;
          getPageResults( page, 'next' );
      
      });
      
      </script>
      

      之后,您可以为上一个和下一个触发器设置一些创意侦听器,并根据需要调用getPageResults() 和所需的页面,以及nextprev 属性。

      这确实可以以更优雅的方式完成 - 查看您提供的示例中的 JS:http://scrollsample.appspot.com/static/main.js

      清理它

      一旦你有了基本的架构,你就可以开始改变.pushState() 以及更改canonicalnextprev &lt;link rel&gt; 标题项。此外,此时您可以开始生成所需的下一个/上一个链接等。一旦奠定了基础,一切都应该到位。

      【讨论】:

      • 您的代码要好得多,谢谢,但我的问题是我需要让工作人员向上或向下滚动以达到 loadPrev 或 loadNext 在这种情况下,而不是获取页面内容 + 1 或页-1。你对此有什么建议吗?
      猜你喜欢
      • 2019-07-05
      • 2012-10-04
      • 1970-01-01
      • 2015-06-03
      • 2017-10-09
      • 2018-10-27
      • 2016-10-17
      • 2021-07-20
      • 2017-08-14
      相关资源
      最近更新 更多