【问题标题】:How to check when image is loaded as a background image?如何检查图像何时加载为背景图像?
【发布时间】:2017-05-12 07:14:11
【问题描述】:

我正在使用此代码,以便在每个.item 上加载页面后,其data-image 应放置为背景图像。问题是 #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 twitter-bootstrap-3 carousel


    【解决方案1】:

    您可以选择包含数据图像的元素,并在该元素使用“完成”功能加载后运行您的 jquery 代码。

    例如:

    if ($("#image").complete) { yourFunction(); }
    

    现在在您的代码中,您希望在 CSS 更改(动画)之后执行代码。您可以使用带有回调的承诺 - 看看 here

    在你的情况下:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多