简体   繁体   English

网页上的div中的“无尽滚动”

[英]'Endless scroll' in a div on a web page

I want to create a div containing endless scrollable content in a page. 我想创建一个在页面中包含无限滚动内容的div。

For recognizing the end of the scrollable content in order to load more data from the data base I've written the following: 为了识别可滚动内容的末尾以便从数据库中加载更多数据,我编写了以下代码:

$(window).scroll(function(){

  var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
  var  scrolltrigger = 0.95;

  if  ((wintop/(docheight-winheight)) > scrolltrigger) {
     lastAddedLiveFunc();
  }
});

Question: The following code is for creating the endless scroll which fits in the entire webpage, but how can I write the same for a 'div' inside a web page? 问题:以下代码用于创建适合整个网页的无限滚动,但是如何为网页内的“ div”写相同的滚动条?

(Hint: An exact similar thing is the Ticker on Facebook, on the right side which shows the recent activities of your friends in real time.) (提示:Facebook上的股票行情器与此类似,它实时显示您朋友的近期活动。)

The principle is the exact same. 原理是完全一样的。 The div will be your browser viewport, and the div content is your document. div将是您的浏览器视口,而div内容是您的文档。 You just need to exchange 您只需要交换

  • $(window).scroll() --> $("#someDiv").scroll() $(window).scroll() -> $("#someDiv").scroll()
  • $(window).scrollTop() --> $("#someDiv").scrollTop() $(window).scrollTop() -> $("#someDiv").scrollTop()
  • $(document).height() --> $("#someDiv")[0].scrollHeight $(document).height() -> $("#someDiv")[0].scrollHeight
  • $(window).height() --> $("#someDiv").height() $(window).height() -> $("#someDiv").height()

and it should work. 它应该工作。

Note that: 注意:

  • scrollHeight is a property, not a function. scrollHeight是属性,而不是函数。
  • scrollHeight isn't jQuery, so you need to obtain it from the actual javascript element of the selector, hence the [0] addition. scrollHeight不是jQuery,因此您需要从选择器的实际javascript元素中获取它,因此需要添加[0] Another way is to use $("#someDiv").prop("scrollHeight"). 另一种方法是使用$(“#someDiv”)。prop(“ scrollHeight”)。
$("#yourdiv").scroll(function(){

//your logic
}

You can use your div instead of window 您可以使用div而不是window

For example 例如

$('#yourdiv').scrollTop()  //  etc

use this 用这个

// 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM