簡體   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