仅在完全加载后淡入背景图像

时间:2014-11-18 09:13:36

标签: jquery css

我正在尝试加载一个大图像背景...即使我使用.load,图像只是正常加载并且在加载后没有平滑的淡入淡出。这是我的代码。

$(function(){
    var bgimage = new Image();      
    bgimage.src="http://placeimg.com/760/460/tech";       

    $(bgimage).load(function(){
        $(".feature").css("background-image","url("+$(this).attr("src")+")").fadeIn(slow);                  
    });
});

演示:http://jsfiddle.net/nud2bfb1/

我做错了什么?

4 个答案:

答案 0 :(得分:6)

尝试此操作:您需要先隐藏图片,然后使用fadeIn()fadeIn(slow)必须fadeIn("slow"),即引号缓慢

$(function(){
    var bgimage = new Image();      
    bgimage.src="http://placeimg.com/760/460/tech";       
    $(".feature").hide();     
    $(bgimage).load(function(){
        $(".feature").css("background-image","url("+$(this).attr("src")+")").fadeIn(2000); 
     }); 
});

<强> DEMO

答案 1 :(得分:2)

您无法检测背景图像上的负载。您无法转换/动画背景图像。

您和其他答案尝试做的是在加载div元素后淡化/动画整个img。这并不是每次都完美无缺。因为,这个IMO具有破坏性,因为整个div(及其内容)必须在加载图像时保持隐藏,或者隐藏div然后尝试淡化它。这会让你闪烁,因为div在淡入淡出之前会突然隐藏。

我建议您使用虚拟img元素,但要将其置于绝对位置(相对于div)且大小相同且为负z-index 。这样,在加载图像时,div及其内容可见。加载后,您将虚拟img淡入(div后面),然后指定background-image,然后删除虚拟img

演示:http://jsfiddle.net/abhitalks/q7cvn2nd/

请参阅此代码段:

&#13;
&#13;
var $img = $("<img />");

$img.load(function() {
    $(this).fadeIn("slow", function() {
        $('.feature').css('background-image', 'url(http://lorempixel.com/240/240)');
        $(this).remove(); 
    });   
});

$img.addClass("dummy");
$img.attr('src', 'http://lorempixel.com/240/240');
$(".feature").append($img);
&#13;
* {
    box-sizing: border-box;
}
.feature {
    position: relative;
    width: 240px; height: 240px;
    border: 1px solid gray;
    padding: 8px; color: #f00; 
    background-color: transparent;
    background-repeat: no-repeat;
    background-size: 100% 100%;
}
img.dummy {
    top: 0; left: 0; bottom: 0; right: 0;
    width: 100%; height: 100%;
    position: absolute;
    z-index: -1;
    display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="feature"><h1>This is some text.</h1></div>
&#13;
&#13;
&#13;

重要不要忘记删除虚拟图片。

答案 2 :(得分:0)

默认显示您的图像。在淡入它之前隐藏它:

<div class="feature" style="display:none;"></div>

FIDDLE http://jsfiddle.net/nud2bfb1/3/

答案 3 :(得分:0)

$(function(){
    var bgimage = new Image();      
    bgimage.src="http://placeimg.com/760/460/tech";       

    $(bgimage).load(function(){
        $(".feature").css("background-image","url("+$(this).attr("src")+")").not(':visible').fadeIn("slow");               
    });
});

demo