[英]'Endless scroll' in a div on a web page
我想創建一個在頁面中包含無限滾動內容的div。
為了識別可滾動內容的末尾以便從數據庫中加載更多數據,我編寫了以下代碼:
$(window).scroll(function(){
var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
var scrolltrigger = 0.95;
if ((wintop/(docheight-winheight)) > scrolltrigger) {
lastAddedLiveFunc();
}
});
問題:以下代碼用於創建適合整個網頁的無限滾動,但是如何為網頁內的“ div”寫相同的滾動條?
(提示:Facebook上的股票行情器與此類似,它實時顯示您朋友的近期活動。)
原理是完全一樣的。 div將是您的瀏覽器視口,而div內容是您的文檔。 您只需要交換
$(window).scroll()
-> $("#someDiv").scroll()
$(window).scrollTop()
-> $("#someDiv").scrollTop()
$(document).height()
-> $("#someDiv")[0].scrollHeight
$(window).height()
-> $("#someDiv").height()
它應該工作。
注意:
scrollHeight
是屬性,而不是函數。 scrollHeight
不是jQuery,因此您需要從選擇器的實際javascript元素中獲取它,因此需要添加[0]
。 另一種方法是使用$(“#someDiv”)。prop(“ scrollHeight”)。 $("#yourdiv").scroll(function(){
//your logic
}
您可以使用div而不是window
例如
$('#yourdiv').scrollTop() // etc
用這個
// get box div position
var box = document.getElementById('box').offsetTop;
window.onscroll = function(){
// get current scroll position
var scroll_top = document.body.scrollTop || document.documentElement.scrollTop;
document.getElementById('scbox').innerText = scroll_top + ' ' + box;
// if current scroll position >= box div position then box position fixed
if(scroll_top >= box)
document.getElementById('box').style.position = 'fixed';
else
document.getElementById('box').style.position = 'relative';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.