繁体   English   中英

当用户滚动到页面底部时,如何自动加载四个隐藏的div?

[英]How to automatically load four hidden divs when the user scrolls to the bottom of the page?

我当前使用的代码一次显示4个div,并在用户单击“加载更多”按钮时又加载4个div。

<script>
$(function() {
  $(".post").slice(0, 4).show();
  $("#loadMore").on('click', function(e) {
    e.preventDefault();
    $(".post:hidden").slice(0, 4).slideDown();
    if ($(".post:hidden").length == 0) {
      $("#load").fadeOut('slow');
    }
  });
});
</script>

我将如何编辑它,以便当用户滚动到父div的底部而不是单击按钮时,会自动显示四个新的div。

加载的前四个div应该是由于用户单击了按钮,从此之后,一旦用户滚动到父div的底部,就应该加载。

<div class="contents">

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>
<div class="post"></div>

</div>

此功能使您可以检查屏幕上是否可见给定节点的百分比。

function isVisible (node, percentage) /* 0.50 = 50% */
{
    var rect = node.getBoundingClientRect();
    var over = rect.height * (1 - percentage);

    return rect.top >= -over && rect.bottom <= window.innerHeight + over;
}

window.addEventListener
(
    "scroll", function ()
    {
        var myParentDiv = document.querySelector("") // here obtain your parent div

        if (isVisible(myParentDiv, 1))
        {
            // when the parent div is 100% visible in the viewport, append your 4 elements.
        }
    }
);

这是一个示例,在添加了4个元素之后,您必须删除侦听器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM