2013-02-06 79 views
1

我在使用JavaScript加载图像时遇到了一些问题。我想要一系列图像顺序加载,即图像2仅在图像1完全加载完成时才开始加载。onLoad事件在图像加载完成之前触发

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

任何想法,我可以等待,直到图像完全加载之前开始加载下一个 - 它不能那么难肯定吗?

注:我最初写它使用jQuery .load功能,得到了相同的结果这就是为什么我被搞乱原JS。

感谢

HTML代码:

<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); 
    }); 

回答

4

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

+0

感谢Marcell我删除了()以便onLoaded不会立即调用,但现在onLoaded函数根本不会被调用。我真的很愚蠢,错过了一些真正重要的东西吗? 我已编辑[JS的小提琴](http://jsfiddle.net/Jm8MR/1/),以反映该变化。 –

+0

挂上,这是我是一个白痴!我正在调用'.onLoad'而不是'.onload'。现在所有人都在工作,谢谢Marcell。 –

1

我相信你从这个错误中看到有人问在2岁前移动了;尽管如此,我认为为了别人的利益,我会指出我认为是你的错误。您使用的是imgObj.onLoad而不是imgObj.onload。 Javascript区分大小写,并且没有原生的“onLoad”事件。

当你解决这个问题时,代码的其余部分应该工作得很好。