![](/img/trans.png)
[英]How to only show a specific number of divs on the page and load more when the user scrolls to the bottom?
[英]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.