【问题标题】:implementing image gallery that lazy loads images of unknown size on scroll and positions them optimally实现图像库,在滚动时延迟加载未知大小的图像并优化定位它们
【发布时间】:2016-07-09 02:22:28
【问题描述】:

我需要实现一个具有以下规范的图片库:

  1. 图像需要具有最大高度和宽度。它们将纵横比保持在这些范围内。

  2. 根据最大尺寸限制后图像的最终尺寸,以减少空白空间的方式在页面上对它们进行排序。

  3. 随着容器向下滚动,加载更多图像。

我研究过的库,例如 masonry 和这个 lay load lib 所有人都希望提前知道宽度和高度。

看来我可能需要以不可见状态加载图像,以便在将它们定位到页面之前获取宽度和高度参数。 这将有助于“砌体”方面,但与延迟加载机制相矛盾。

我将不胜感激任何正确方向的指示。

【问题讨论】:

    标签: javascript jquery html css image


    【解决方案1】:

    我现在正在使用 Masonry,我认为它符合您的需求。我有不同的宽度和高度图像,我加载了固定的最大宽度(具有固定宽度或相对于第一页的宽度),然后,布局重新排序以避免空白并保持图像的纵横比。当我到达页面底部时,我(“手动”)加载更多项目。这是我的代码

    //Load the first page
    loadMore(1);
    
    function loadMore(page){ 
        var div = "";
        var html = "";
        var item_num = 1 + ((page-1)*10);
    
        $('.loader').show();
        $('#container').hide();
    
        $.post( "loadMore.php", {'page':page }, function( data ) { 
            data=JSON.parse(data);
            $.each(data, function (key,value) {
              //here create the div with the data
              html = html + div;                                                                 
              item_num++;   
            }); 
    
            $("#container").append(html).each(function(){                              
            $('#container').masonry().masonry('reloadItems');
            });            
    
            var $container = $('#container');
            $container.imagesLoaded(function(){
              $('#container').masonry();
            }); 
    
            $('.loader').fadeOut('fast',function(){
            $(this).remove().delay( 1500 );
            });
            $('#container').show();                        
    
        });
    }
    
    //On bottom page, load more images
    $(window).scroll(function () {
        if (ready && $(document).height() <= $(window).scrollTop() + $(window).height()) {
            ready = false; //Set the flag here  
    
            setTimeout(function(){
            loadMore(page);                
            page++;
            },1000);
    
            ready = true; //Set the flag here  
        }
    });
    

    你可以在http://pintevent.com查看结果(是一个测试页面)

    然后,很容易将 LazyLoad 添加到所有图像,这是一个工作示例: http://jsfiddle.net/nathando/s3KPn/4/(摘自类似问题:Combining LazyLoad and Jquery Masonry

    另外,如果它不适合你,这里有一堆 jquery LazyLoad 库供你查看:http://www.jqueryrain.com/demo/jquery-lazy-load/

    希望对你有帮助!

    【讨论】:

    • 感谢您提供完整的代码示例,并附有工作示例和相关示例的链接。非常高质量的答案!顺便说一句,您可以通过在顶部定义 $container 并始终引用 $container 而不是使用 $('container') 进行新查询来优化 loadMore 函数。
    • 谢谢!以后我会这样做的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多