Jquery 如何检查图像何时作为背景图像加载?

Jquery 如何检查图像何时作为背景图像加载?,jquery,twitter-bootstrap-3,carousel,Jquery,Twitter Bootstrap 3,Carousel,我使用此代码是为了在每个上加载页面后,将其数据图像作为背景图像放置。问题在于,只有在(至少)加载了第一个图像后,#loadingsvg才会淡出。我该怎么查呢 <div id="myCarousel"> <div class="item" data-image="asdf.jpg"></div> <div class="item" data-image="asdf2.jpg"></div> <div clas

我使用此代码是为了在每个
上加载页面后,将其
数据图像
作为背景图像放置。问题在于,只有在(至少)加载了第一个图像后,
#loadingsvg
才会淡出。我该怎么查呢

<div id="myCarousel">
    <div class="item" data-image="asdf.jpg"></div>
    <div class="item" data-image="asdf2.jpg"></div>
    <div class="item" data-image="asdf23.jpg"></div>
</div>

jQuery(window).load(function() {
    jQuery('#myCarousel .item').each(function(){

        // Take data-image
        var $this = jQuery(this),
        src = $this.data('image');

        if (typeof src !== "undefined" && src != "") {
            // Set as background image
            $this.css('background', 'url(' + src + ')');
        }

        jQuery('#loadingsvg').fadeOut();

    });

});

jQuery(window).load(函数(){
jQuery('#myCarousel.item')。每个(函数(){
//拍摄数据图像
var$this=jQuery(this),
src=$this.data('image');
如果(类型src!=“未定义”&&src!=“未定义”){
//设置为背景图像
$this.css('background','url('+src+'));
}
jQuery('#loadingsvg').fadeOut();
});
});

您可以选择包含数据图像的元素,并在该元素加载函数“complete”后运行jquery代码

例如:

if ($("#image").complete) { yourFunction(); }
现在在代码中,您希望在css更改(动画)后执行代码。你可以用一个带回叫的承诺

就你而言:

if (typeof src !== "undefined" && src != "") {
            // Set as background image
            $this.css('background', 'url(' + src + ')').promise().done(function(){
                  jQuery('#loadingsvg').fadeOut();;
});
或者,一个不那么优雅的解决方案:您可以在淡出前添加一个超时,如下所示:

setTimeout(function(){jQuery('#loadingsvg').fadeOut();}, 1000);