我在使用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);
});
感谢Marcell我删除了()以便onLoaded不会立即调用,但现在onLoaded函数根本不会被调用。我真的很愚蠢,错过了一些真正重要的东西吗? 我已编辑[JS的小提琴](http://jsfiddle.net/Jm8MR/1/),以反映该变化。 –
挂上,这是我是一个白痴!我正在调用'.onLoad'而不是'.onload'。现在所有人都在工作,谢谢Marcell。 –