简体   繁体   English

jQuery 滚动显示隐藏内容

[英]jQuery scroll show hidden content

How do I make it so that by default, 6 div elements are shown on the page, and when a user scrolls to the bottom of the page, six more are loaded?我该如何做到默认情况下页面上显示 6 个 div 元素,当用户滚动到页面底部时,会加载另外六个元素?

If you see this example , it has multiple divs.如果您看到这个例子,它有多个 div。 I want only 6 of them to be show initially, and each time the user reaches the bottom of the page, I want six more to be loaded, until you 'run out' of divs.我希望最初只显示其中的 6 个,每次用户到达页面底部时,我希望再加载六个,直到你“用完”div。

So far I have tried experimenting with jQuery infinite scroll plugins, but they are not applicable in my case, as in fact the number of elements I have is very finite!到目前为止,我已经尝试使用 jQuery 无限滚动插件进行试验,但它们不适用于我的情况,因为事实上我拥有的元素数量非常有限!

How can this be accomplished using jQuery?如何使用 jQuery 完成此操作? Thanks in advance!提前致谢!

EDIT编辑

I believe one could set the rest of the divs to hidden (apart from the first 6), and trigger a function that loads six more when the bottom of the page is reached.我相信可以将 div 的 rest 设置为隐藏(除了前 6 个),并触发一个 function,当到达页面底部时再加载六个。

I have created a very quick example, it's not optimised by does the job:我创建了一个非常简单的示例,它没有通过工作进行优化:

http://jsfiddle.net/gRzPF/2/ http://jsfiddle.net/gRzPF/2/

You should be able to use something like the following:您应该能够使用如下内容:

jQuery( window ).scroll( function( ) {
    var loadHeight = jQuery( document ).height( ) - jQuery( window ).height( );
    if( haveDivsToLoad && jQuery( window ).scrollTop( ) >= loadHeight ) {
        // fire your load function here
    }
} );

You might need to play with loadHeight to make it work to your satisfaction.您可能需要使用loadHeight来使它的工作令您满意。

EDIT: I added haveDivsToLoad to the check.编辑:我在检查中添加了haveDivsToLoad You should make this a global (or closure) variable and set it to true or false depending on whether there are more div s to load.您应该将其设为全局(或闭包)变量,并根据是否有更多div要加载将其设置为truefalse

Lets assume you have an array of divs each initialized with the document.createElement("div") or similar.假设您有一个 div 数组,每个 div 都使用document.createElement("div")或类似方法初始化。 Lets assume you have a large array of them.让我们假设你有一大堆。

var myArrayOfDivs = [];//see above
var DivsAdded = 6;//as stated, 6 were already added - index 6 is the 7th element
$(window).scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {
        for(int i = 0; i < 6; i++){
         if( myArrayOfDivs.length < DivsAdded ) break;
         $("#elementToAppendIn").append(myArrayOfDivs[DivsAdded++]);
        }
    }
});

After a bit of experimenting, I found the perfect answer:经过一些试验,我找到了完美的答案:

http://jsfiddle.net/jackdent/gRzPF/12/ http://jsfiddle.net/jackdent/gRzPF/12/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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