【问题标题】:load remote images via Javascript, then selectively add to array通过 Javascript 加载远程图像,然后有选择地添加到数组
【发布时间】:2010-06-27 01:08:20
【问题描述】:

我正在尝试使用 javascript 加载不在当前页面上的图像(来自图像链接数组),如果它们足够大,请将它们添加到数组中。我在当前页面加载后执行此操作,通过小书签或萤火虫控制台。使用FF。

我最接近的是下面,但这似乎不起作用,我猜这是因为尺寸测试在图像加载之前运行。显然我试图用'onload'解决这个问题是行不通的。我该如何解决这个问题,或者是否有更好/更简单的方法来完成这项任务?

(function() {

    //create array for the images
    var imageArray = new Array();


    function loadIfBig(x){
            if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
                imageArray.push(x);
                //dispImage = '<img src=' + x.src + '><br>';
                //document.write('<center>' + dispImage + '</center>');
            }
        return true;
    }


    //given an array of imageLinks:
    for (x in imageLinks){
    //create an image form link and add to array if big enough
        im = document.createElement('img');
        im.src = imageLinks[x];
        im.onload = loadIfBig(im);
    }

    //view results:

    for (x in imageArray){
        disp_image = '<img src='+imageArray[x].src+'><br>';
        document.write('<center>'+disp_image+'</center>');
    }


})();

更新:

谢谢!确定你是对的,我在这里遗漏了一些愚蠢的东西,但我做了你建议的改变,然后将元素写入 loadIfBig,但它似乎没有执行该函数。下面的当前代码,包括几个示例输入链接:

(function() {
    var imageArray = new Array();

    var imageLinks = ['http://1.bp.blogspot.com/_mfMRTBDpgkM/SwCwu1RPphI/AAAAAAAAJpw/v9YInFBW84I/s1600/800px-San_Francisco_in_ruin_edit2.jpg','http://2.bp.blogspot.com/_mfMRTBDpgkM/SwCwulSZ_yI/AAAAAAAAJpo/NsRcJdpz4Dk/s1600/San_Francisco_PC_59.jpg']

    function loadIfBig(x){
            if (x.height > 299 && x.width > 299 && (x.height > 399 || x.width > 399)) {
                imageArray.push(x);
                dispImage = '<img src=' + x.src + '><br>';
                document.write('<center>' + dispImage + '</center>');
            }
            return true;
    }
    processImages = function(){
        for (x in imageLinks) {
            //create an image from link and add to array if big enough
            im = document.createElement('img');
            im.src = imageLinks[x];
            im.onload = function(){
                loadIfBig(this);
            }
        }

    }       
})();

【问题讨论】:

    标签: javascript image loading


    【解决方案1】:

    您的修复不起作用,因为您实际上是立即执行它。

    im.onload = loadIfBig(im) 实际上是运行函数。

    你可以做的是这样的:

        im.onload = function() {
            loadIfBig(this); 
        }
    

    另一个问题是,在实际执行 onload 回调之前,您正在运行大图像数组。这需要停留在不同的函数中,并在所有加载完成后调用。

    【讨论】:

    • @kiamlaluno 是的,我在一次编辑中意识到了这一点。谢谢
    • 谢谢。试图采纳您的建议,但似乎不起作用。 (见更新)对不起,如果我在这里很密集。
    • processImages 不需要是函数。您可以立即执行该部分。完成所有这些之后,它应该可以正常工作。 (现在的方式,processImages 永远不会执行)
    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多