onLoad事件在图像加载完成之前触发

时间:2013-02-06 17:12:56

标签: javascript jquery onload

我在JavaScript中加载图像时遇到了一些问题。我想要一系列图像按顺序加载,即图像2仅在图像1完全加载时开始加载。

我发现的问题是,当图像完成加载时,JavaScript onLoad方法不会触发,但是当图像开始加载时。因此,无论队列中的哪个位置,最小的图像始终是第一个加载的图像。我把a simple example of what i mean放在JS小提琴中(HTML和JS代码也在下面)。

在开始加载下一张图片之前我是否可以等到图像完全加载之后的任何想法 - 这肯定不是那么难吗?

注意:我最初使用jQuery .load函数编写它并得到了相同的结果,这就是我在原始JS中搞乱的原因。

由于

HTML code:

<ul>
    <li><img src="" alt="image 1" width="210" height="174"></li>
    <li><img src="" alt="image 2" width="210" height="174"></li>
    <li><img src="" alt="image 3" width="210" height="174"></li>
    <li><img src="" alt="image 4" width="210" height="174"></li>
    <li><img src="" alt="image 5" width="210" height="174"></li>
</ul>

<a href="#" id="loader">Load the images</a>

JS代码:

        var imgArr = [
        "http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/zine-HP-UK.jpg",
        "http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/Valentine_UK.jpg",
        "http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/crop_UK__.jpg",
        "http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/hitlist_UK--.jpg",
        "http://media.topshop.com/wcsstore/ConsumerDirectStorefrontAssetStore/images/colors/color7/cms/pages/static/static-0000038166/images/chinese_new_year_UK_new_0402.jpg"
    ],
    totalImgs = imgArr.length,
    count = 0;

    function onLoaded(count) {
        console.log("fired onload "+count);
        var currentImg = $('li:eq('+count+') img');
        currentImg.attr('src', imgArr[count]).css('display','block');
        count++;
        if (count < totalImgs) {
            loadImg(count);
        };
    }

    function loadImg(count) {
        imgObj = new Image()
        imgObj.src = imgArr[count];
        imgObj.onLoad = onLoaded(count);                        
    }

    $('#loader').click(function() {
        loadImg(count);
    });

2 个答案:

答案 0 :(得分:4)

这里的问题是,处理函数不是分配给onload的{​​{1}}事件,而是Image的返回值。您需要说onLoaded对于imgObj.onload = onLoaded;,您可以使用currentImg,因为将在this对象上调用处理程序。要传递其他参数,需要另一种方法。

答案 1 :(得分:1)

我确定你从这个错误开始,看到它是在2年前被问到的;尽管如此,我认为为了别人的利益,我会指出我认为是你的错误。

您正在使用imgObj.onLoad而不是imgObj.onload。 Javascript区分大小写,并且没有本地&#34; onLoad&#34;事件。

当您解决此问题时,其余代码应该可以正常运行。

相关问题