【问题标题】:image onload trouble图片加载问题
【发布时间】:2012-10-30 02:04:26
【问题描述】:

我正在创建一个大页面,其中包含很多包含大背景图像的块,所以我认为最好的办法是显示预加载器并在后台加载图像并更新加载器(20 幅中的第 4 幅,ecc) .我的问题是:当 onload 事件触发我的加载器时,我的加载器消失但我仍然看到图像加载,这意味着它没有完全加载。为什么会这样?有什么想法吗?

这是页面:

http://zhereicome.com/experiments/statics/myascensor/#1-1

提前致谢

nImages = $('.slide').length;
loadedImgs = 0;
var bgImages = ['img/bbb.png','img/bbb2.png','img/bbb3.png'];

$('.slide').each(function(i){
    var curSlide = $(this);
    var img = new Image();
    img.src = bgImages[ i % 3 ];
    img.onLoad = imageLoaded(img, curSlide);
})    

function imageLoaded(img, curSlide){
    curSlide.css('backgroundImage', 'url(' + img.src + ')');
    loadedImgs++;
    if(nImages == loadedImgs){
        $('#container').css('visibility','visible');
        $('#loader-cont').fadeOut(1000);
    }
    $('.loader-inner .title').text(loadedImgs / nImages);
}

【问题讨论】:

  • 另外,模式是 img.onload = someFunc; 那么 img.src = someFile;在尝试加载文件之前,您必须告诉它在文件加载时要做什么。如果图像已经被缓存,你可以很容易地不触发 onload 事件。它可能“有效”(大部分),但它不是正确的方法。

标签: javascript onload


【解决方案1】:

您似乎在使用 window.onload 和 document.ready 时遇到了一些问题:

$(document).ready(function(){
// This will be executed when the DOM is ready.
});

$(window).load(function(){
// This will be executed when the whole document and all its 
// referenced items (style sheets, scripts, images, etc.) are loaded.
});

但这已经被问过了,而且回答得好多了:How can I create a "Please Wait, Loading..." animation using jQuery?

【讨论】:

  • 感谢 elcodedocle,但添加加载动画并在窗口加载时将其删除并不是我想要的。我想要的是一个带有百分比的加载屏幕。无论如何,我这样解决: $(img).load(function(){ curSlide.css('backgroundImage', 'url(' + img.src + ')'); loadedImgs++; if(nImages == loadedImgs){ $('#container').css('visibility','visible'); $('#loader-cont').fadeOut(1000); } $('.loader-inner .title').text('正在加载...' + ((loadedImgs / nImages) * 100) + '%'); })
猜你喜欢
  • 2014-06-11
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多