【问题标题】:Loading and appending images progressively逐步加载和附加图像
【发布时间】:2011-07-10 01:54:57
【问题描述】:

我有一个无法解决的问题。我做了一个简单的jQuery相册画廊,我有这个功能:

function loadAlbum (index) {
    for (var j=1; j < xmlData[index].length; j++) {

        var img = new Image();

        $(img).load(function() {
                    $(this).hide();
                    $('#album'+index+' .photoContainer').append(this);
                    $(this).fadeIn();
                })
                .error(function(){
                    //alert("Could not load one or more photo!");
                })
                .attr({
                    'src': xmlData[index][j],
                    'id': 'img'+index+j,
                    'class': 'photoFrame',
                    'width': newW,
                    'height': newH
                })
                .css({
                    'width': newW,
                    'height': newH
                });
    };
};

现在,您可以看到所有图像 src 都是从包含数据的外部 XML 文件导入的(图像名称是渐进式的,例如:photo001.jpg、photo002.jpg 等)。

它们通过 for 循环在 DOM 中创建并附加到 div。

你可能会说什么问题?我需要以 XML 数据中指定的渐进方式附加所有图像,但这仅发生在本地计算机上,而不是在某些服务器上上传时。我发现这是由于每个图像的加载时间取决于大小......但我仍然无法弄清楚如何解决这个问题。有人知道吗?

【问题讨论】:

    标签: jquery image load gallery


    【解决方案1】:

    以下尝试一次加载一张图片。加载图像后,将加载集合中的下一个图像。

    function loadAlbum(index) {
        var i = 0;
        var j = xmlData[index].length;
        function loadImage() {
             if (i >= j) return;
    
             // do what you're doing in the loop except for ....
             $(img).load(function() {
                 $(this).hide();      
                 $('#album'+index+' .photoContainer').append(this);
                 $(this).fadeIn();
                 // increments i by 1 and calls loadImage for the next image.
                 i++;
                 loadImage();
             // etc.
        }
        loadImage();
    }
    

    我把它作为一个练习让你确定如何一次加载多个图像并仍然保持顺序:)

    【讨论】:

    • 天啊,非常感谢:D!一切都很顺利和完美......现在我觉得自己像个真正的菜鸟 XD!
    猜你喜欢
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多