加载后淡入带有背景图像的Div

时间:2014-02-23 06:55:16

标签: jquery html css css-transitions

我正在尝试淡入div,其中包含内嵌背景图片。

我已经在页面加载的图片上尝试过了,但我们怎样才能在div中使用背景图片实现这种效果。

4 个答案:

答案 0 :(得分:3)

您可以使用名为waitForImages的jQuery插件,该插件可以检测下载背景图片的时间。

$('selector').waitForImages({
    finished:function(){$(this).slideUp();},
    waitForAll:true
});

答案 1 :(得分:2)

评论中链接的问题的第二个答案Link here提供了一个解决方案,您可以将背景图像加载到图像标记,然后在准备就绪时将图像注入div。这是一个类似但不同的例子:

HTML:

<img src="http://www.modernmythmedia.com/wp-content/uploads/2013/04/Iron-Man-wallpaper-2-2032-e1367196003357.jpg" id="dummy" style="display:none;" alt="" />
<div id="pic" style="height:100px;width:100px;display:none;"></div>

jQuery的:

$('#dummy').ready(function() {
    $('#pic').css('background-image','url(http://www.modernmythmedia.com/wp-content/uploads/2013/04/Iron-Man-wallpaper-2-2032-e1367196003357.jpg)');
    $('#pic').fadeIn(1000);
});

在此处进行实时预览:Fiddle

希望这对您更有效!

答案 2 :(得分:0)

HTML5动画将加载允许this and more的画布上下文。

Here是动画的CSS演示。

答案 3 :(得分:-1)

你能试试吗?

<强> HTML

<div id="mg" style="background-image:url(http://lorempixel.com/1920/1920/); display:none; width:1920px; height:1920px;"></div>

<强> JS

var elem   = $('#mg'),
    bgImg  = elem.css('background-image'),
    imgUrl = bgImg.indexOf('"')!=-1 ? 
             bgImg.replace('url("','').replace('")','') : 
             bgImg.replace('url(','').replace(')',''),

     nwImg = new Image();
     nwImg.src = imgUrl;

nwImg.onload = function() {
    elem.fadeIn('fast');
}

nwImg.onerror = function() {
    alert('error');
}

<强>的jsfiddle

http://jsfiddle.net/EZg36/8/

如果您错误地更改了网址,您会看到错误消息(例如:background-image:url(hERRRttp://lorempixel.com/1920/1920/);)