我在一个页面上有大约四百张图片,我想在图片加载到页面上时向用户显示一个增量计数器。它在 Firefox 中运行良好,但我在 IE 和 Chrome 中遇到问题。
var increment ={
start: function(){
$updateThree = $('.container').children('img').length;
increment.countImagesLoading();
getCount = setInterval(increment.updateImagesLoading,100);
},//end function
countImagesLoading:function(){
imgCount = 0;
$img = $('.container').children('img');
$img.one('load',function() {
imgCount++;
});
},
updateImagesLoading: function(){
$colThree.html('<strong>'+imgCount+'</strong>');
if(imgCount == $updateThree){
clearInterval(getCount);
//end the interval because all the images are loaded!
}
},
}
$(document).ready(increment.start);//document.ready
我还删除了间隔和对 updateImagesLoading
的调用刚刚有了 countImagesLoading
函数也使用每个 .load 函数更新屏幕上的值,但无论我使用哪种方法,我仍然得到相同的结果:
Firefox,它可以工作。
Chrome,它可以工作,但最终与页面上应该加载的图像的真实数量 (464) 相差 15 到 20。
IE,不通过 $colThree.html('<strong>'+imgCount+'</strong>');
显示计数更新。直到所有图像都完全加载,所以它是空白的,然后显示 464。
最佳答案
这里我认为问题在于此脚本在 ready
事件上执行,但图像在 DOM 中找到后立即开始加载。
如果您能以某种方式将所有图像的 src 更改为一个加载图像并将实际的 src 放在其他属性(如 data-src)中,则问题应该可以解决。然后在就绪事件中占用每张图片并加载图片,从 data-src 属性中获取 url。当它在 JS 中完全加载时,将提供图片的 url。
$('img').each(function(){
var src = $(this).data('src');
var img = new Image();
img.load = function(){
/*increase count here and set the src of the DOM img element*/
};
img.src = src;
});
关于javascript - 如何在使用 Javascript 在 Chrome 中加载图像时对它们进行计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18503484/