[英]HTML Load elements in a blank page
我有一個空的 HTML 頁面,只有一個div
和一個用於加載數據的button
。
<body>
<div id="main_div"></div>
<button class="load_more" onclick="myFunction()">Load More..</button>
</body>
myFunction
是一個 function ,它創建並填充 div main_div
。 我想從中創建一個無限滾動視圖。 我添加了滾動監聽器,它調用myFunction
並在只剩下 200px 時加載數據。 (我從網上的博客得到這個代碼)
$(window).on('scroll', function() {
console.log('Scroll detected')
var scrollHeight = $(document).height();
var scrollPos = Math.floor($(window).height() + $(window).scrollTop());
var isBottom = scrollHeight - 200 < scrollPos;
if (isBottom && currentscrollHeight < scrollHeight) {
$('.load_more').click();
currentscrollHeight = scrollHeight;
}
});
當我手動點擊加載按鈕幾次並且頁面加載了元素時,無限滾動工作正常。 之后,當我滾動時,它會加載新數據。
但我想要的是從同一個 API 填充初始空間。 我想多次調用同一個 function,但我不確定我應該調用多少次,因為該頁面可以從手機或任何瀏覽器打開,我不知道它的高度。
另外,我想避免使用 JQuery 或其他框架以使其最小化。 我知道代碼已經在使用 JQuery,但我打算刪除它。
您可以調用 function 它將檢查您的div
高度並將其與windowHeight
進行比較。 直到div
高度小於windowHeight
你應該稱之為 function
喜歡
document.addEventListener("DOMContentLoaded", function(e) {
function loadData(callBackFunction) {
// your function body
// in your ajax success request add following line
if (callBackFunction) {
callBackFunction();
}
}
function loadInitialData() {
if (document.getElementById('main_div').getBoundingClientRect().height < window.innerHeight) {
loadData(loadInitialData);
}
}
(function() {
loadInitialData();
})();
// Also Your click event won't work here(inside the listener function).
// So it isn't visible outside of this function's scope.
// If you want to call the method directly 'from the button', then you have to attach it to `window`
window.loadData = loadData;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.