jQuery 无限滚动不触发

问题描述 投票:0回答:4

我正在制作一个简单的小网站,以对 Reddit 帖子应用不同的格式样式,我正在尝试添加无限滚动 jQuery 插件,但它没有执行任何操作。我尝试按照无限滚动页面上的(非常简单)说明进行操作,当它没有执行任何操作时,我认为我一定输入了错误的内容,但后来我只是从 Masonry/Infinite-Scroll example 复制/粘贴了代码 但还是没用。砌体工作完美(最终),但我只是无法弄清楚无限滚动出了什么问题。我了解 jQuery 和 JavaScript 的基础知识,但显然不如你们大多数人了解得那么多,所以您能帮我一下,让我知道哪里出了问题吗?我的网站已上线:reddit.ymindustries.com

非常感谢,到目前为止你们很少让我失望。

YM

编辑:如果主页上的图像不足以填满页面,请访问 reddit.ymindustries.com/r/aww 获取更多图像。

编辑2:我相信我找到了问题,如下所述:https://github.com/paulirish/infinite-scroll/issues/5 现在要找出解决办法...

编辑3:添加了一些技巧以使其能够正常工作,但现在似乎只是无休止地循环第二页。嗯...

javascript jquery jquery-masonry infinite-scroll
4个回答
0
投票

我认为你的问题实际上是CSS。使页面的长度超过客户区域的高度。将更多图像添加到 $container

要点是, $container 的底部边缘需要通过窗口底部,因此滚动事件会触发,因此无限滚动可以对此事件做出反应并计算天气或未到达边缘

顺便说一句,在同样的情况下,例如,当我缩小窗口时,您设置的示例正在工作。

===更新===

我找到了一些时间来玩无限滚动,这是最终的工作脚本,只需在脚本中设置 pathParse 方法

$(function () {

        var $container = $('#itemContainer');

        $container.imagesLoaded(function () {
            $container.masonry({
                itemSelector:'.item'
            });
        });
        $container.infinitescroll({
                    navSelector:'.navigation', // selector for the paged navigation
                    nextSelector:'.navigation #next', // selector for the NEXT link (to page 2)
                    itemSelector:'.item', // selector for all items you'll retrieve
                    bufferPx:40,
                    debug:true,
                    columnWidth:function (containerWidth) {
                        return containerWidth / 5;
                    },
                    loading:{
                        finishedMsg:'No more pages to load.',
                        img:'http://i.imgur.com/6RMhx.gif'
                    },
                    pathParse: function(path,page){
                        return $(this.nextSelector).attr("href");
                    }
                },
                // trigger Masonry as a callback
                function (newElements) {
                    // hide new items while they are loading
                    var $newElems = $(newElements).css({ opacity:0 });
                    // ensure that images load before adding to masonry layout
                    $newElems.imagesLoaded(function () {
                        // show elems now they're ready
                        $newElems.animate({ opacity:1 });
                        $container.masonry('appended', $newElems, true);
                    });
                    //console.log("test (never fired :( )");
                }
        );

    });

现在,由于您的下一个链接不会自行更新(http://reddit.ymindustries.com/?after=t3_yh4av),您需要更改回调以从ajax响应中提取最后一个元素并更改下一个链接。 .可能是这样的

function (newElements) {
                        // hide new items while they are loading
                        var $newElems = $(newElements).css({ opacity:0 });
                        // ensure that images load before adding to masonry layout

                        // ======> if query parameter after=... is caring filename then do this
                        var lastImageUrl= $newElements[$newElements.length-1].attr("src");
                        var lastFileName= lastImageUrl.substring(lastImageUrl.lastIndexOf("/") +1, lastImageUrl.lastIndexOf("."));
                        $("#next").attr("href", "http://reddit.ymindustries.com/?after="+lastFileName);

                        $newElems.imagesLoaded(function () {
                            // show elems now they're ready
                            $newElems.animate({ opacity:1 });
                            $container.masonry('appended', $newElems, true);
                        });
                        //console.log("test (never fired :( )");
                    }

0
投票

您还需要注意您使用的无限滚动版本,因为如果您使用砖石/同位素(版本 2.0b2.110713)附带的版本,则两者都需要一些技巧才能调用该函数而不是使用预定义数组:

//old code, to be changed (line 489)
desturl = path.join(opts.state.currPage);
// new code
desturl = (typeof path === 'function') ? path(opts.state.currPage) : path.join(opts.state.currPage);

这已经在新版本的无限滚动中修复了


0
投票

我对 jQuery 的“infinitescroll”和 Masonry 也有同样的问题。您可以通过为页面提供更多初始项目来解决此问题,以便插件的滚动检测启动。

在 WordPress 中,它位于“阅读”设置下。默认情况下,WordPress 一次仅打开 10 个项目。您可以将该数字增加到 100/页,以更确保窗口最初会被填满。我这里有一些代码非常糟糕,结果我只需要更长的页面,而不是更多的代码。

因此,如果没有足够的图像,则很难在大显示器上测试这些插件。也许解决方案是在大显示屏上将图像缩放得更大,这样您就可以更确定将内容显示在首屏以下。

如果您认为有人可能会通过非常大的显示屏访问您的网站,那么除了显示更多项目/页面之外,我不确定答案是什么,并且可能会在页脚中添加

$('#masonry').infinitescroll('retrieve');
以加载额外的页面以防万一。


0
投票

尝试这个代码,我认为它可能会有所帮助:

<!DOCTYPE html>
<html>
  <head>
    <title>Infinite Scroll Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
      #content {
        height: 1000px;
        background-color: lightblue;
        margin-bottom: 50px;
      }

      #loading {
        display: none;
        text-align: center;
        font-size: 18px;
        color: gray;
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <div id="content">
      <p>Some initial content here...</p>
    </div>
    <div id="loading">Loading more content...</div>
    <script>
      // Function to check if the user has scrolled to the bottom of the page
      function isScrolledToBottom() {
        const scrollTop = $(window).scrollTop();
        const windowHeight = $(window).height();
        const documentHeight = $(document).height();
        return scrollTop + windowHeight >= documentHeight;
      }

      // Function to load additional content using AJAX
      function loadMoreContent() {
        $('#loading').show();
        $.ajax({
          url: 'load-more-content.php',
          method: 'GET',
          data: { offset: $('#content p').length },
          success: function(html) {
            $('#content').append(html);
            $('#loading').hide();
          }
        });
      }

      // Event listener for scrolling
      $(window).scroll(function() {
        if (isScrolledToBottom()) {
          loadMoreContent();
        }
      });
    </script>
  </body>
</html>

此代码创建一个滚动页面,在 id 为“content”的元素中包含一些初始内容。无限滚动功能是使用jQuery和AJAX实现的。

您需要在服务器上创建 load-more-content.php 脚本,以根据 offset 参数动态生成附加内容。该脚本应返回要附加到页面的 HTML 内容。

这是 load-more-content.php 脚本:

<?php
// Connect to the MySQL database
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';
$conn = mysqli_connect($host, $username, $password, $database);

// Retrieve the offset parameter from the AJAX request
$offset = isset($_GET['offset']) ? $_GET['offset'] : 0;

// Query the database for additional content
$sql = "SELECT * FROM posts LIMIT $offset, 10";
$result = mysqli_query($conn, $sql);

// Generate HTML code for the additional content
$html = '';
while ($row = mysqli_fetch_assoc($result)) {
  $html .= '<p>' . $row['title'] . '</p>';
  $html .= '<p>' . $row['content'] . '</p>';
}

// Return the HTML code to the AJAX request
echo $html;

// Close the database connection
mysqli_close($conn);
?>

© www.soinside.com 2019 - 2024. All rights reserved.