根据页面滚动显示div,如Infinite scroll



我有这个页面有很多信息,这使得我的页面加载时间慢。所以我找到了这个神奇的代码来加载更多的按钮。我想弄清楚如何做到这一点没有加载更多的按钮和显示div自动滚动。下面是代码:

Codepen演示
<link rel="stylesheet" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css">
<div class="container">
<div class="flex">
<div class="content">Box 1</div>
<div class="content">Box 2</div>
<div class="content">Box 3</div>
<div class="content">Box 4</div>
<div class="content">Box 5</div>
<div class="content">Box 6</div>
<div class="content">Box 7</div>
<div class="content">Box 8</div>
<div class="content">Box 9</div>
<div class="content">Box 10</div>
</div>

<a href="#" id="loadMore">Load More</a>
</div>
<style>
.flex {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.content {
height: 100px;
width: 45%;
color: #fff;
font-size: 24px;
line-height: 100px; /* centering text just for view */
text-align: center;
background-color: grey;
margin: 5px;
border: 1px solid lightgrey;
display: none;
}
#loadMore {
width: 200px;
color: #fff;
display: block;
text-align: center;
margin: 20px auto;
padding: 10px;
border-radius: 10px;
border: 1px solid transparent;
background-color: blue;
transition: .3s;
}
#loadMore:hover {
color: blue;
background-color: #fff;
border: 1px solid blue;
text-decoration: none;
}
.noContent {
color: #000 !important;
background-color: transparent !important;
pointer-events: none;
}
</style>
<script>
$(document).ready(function(){
$(".content").slice(0, 4).show();
$("#loadMore").on("click", function(e){
e.preventDefault();
$(".content:hidden").slice(0, 4).slideDown();
if($(".content:hidden").length == 0) {
$("#loadMore").text("No Content").addClass("noContent");
}
});

})
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

有人能帮忙吗?非常感谢。我尝试了很多无限卷轴,大多数都是太多的代码。我想做一件很简单的事。

如果你正在使用jQuery,这很容易实现与滚动事件和一些计算:

loadMoreScroll( element ) {
// Are we loading more items? Prevent duplicate ajax requests.
let loadingMore = false;
element.scroll(function() {
if (loadingMore) return;
loadingMore = true;
// This is the bottom position of your browser right now.
let pageBottom = $(window).scrollTop() + $(window).height();
// This is the bottom position of the container
let containerBottom = $(this).offset().top + $(this).height();
// Give some space to start loading more items before touching the bottom.
let margin = 50;
// Now check if by scrolling you reached the end of the container:
if (pageBottom >= containerBotton - margin) {
// Ajax load more here
// If there are more items to load:
loadingMore = false;
// If no more items to load, leave 'loadingMore' to true, so
// all this code doesn't get executed anymore.
}
});
}
loadMoreScroll( $("#myContainer") );

最新更新