只有在完全加载后才加载背景图片? [英] Only load the background-image when it has been fully loaded?
问题描述
如何在完全加载后动态加载背景图片?有时候,我必须使用非常大的背景,以至于浏览器可能需要一段时间才能下载它。我宁愿'加载它在后台',并让它在完全加载时淡入。
我认为jQuery最好使用,但我如果JavaScript已被禁用,也希望我的背景出现。如果这真的不可能,那就这样吧,但我认为它是这样的?
最好的问候,
Aart
........
编辑:
谢谢你们,伙计们!我已经被这个问题困扰了很长时间,只是想不出一个简单易用的方法。
我将Jeffrey的Javascript解决方案转换为jQuery版本,只是因为
如果其他人有同样的问题,我会在这里发布它:
< script type ='text / javascript'src ='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min的.js'>< /脚本>
< script type ='text / javascript'>
$(document).ready(function(){
$('#img')。css('opacity','0')。load(function(){
$这个).animate({
opacity:1
},500);
});
});
< / script>
< img src ='yourimage.jpg'id ='img'/>
如果图片是 img
元素:
< img src =bg.jpgid =imgonload =this .style.opacity ='1'/>
< script> document.getElementById(img)。style.opacity =0;< / script>
如果JavaScript禁用,应该正常加载图像,但是只有在加载后才显示它,假设它已启用。
有一点需要注意(我忽略了);如果 display 属性为
none
,则某些浏览器甚至不会尝试加载图像。这就是为什么此方法使用不透明属性
属性。
Well, the title pretty much describes my question:
How to load the background-image dynamically after it has been fully loaded? Sometimes, I must use backgrounds that are so big that it can take a while for the browser to download it. I'd rather 'load it in the background' and let it fade in when it has been fully loaded.
I think jQuery would be best to be using, but I also want my background to appear if JavaScript has been disabled. If this really isn't possible, so be it, but I think it is?
Best regards, Aart
........
EDIT:
Thanks a bunch, guys! I've been bugged with this for ages and just couldn't think of a nice and easy way.
I converted Jeffrey's Javascript-solution into a jQuery one, just because jQuery's built-in fade looks so awesome.
I'll just post it here in case anyone else has the same issue:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#img').css('opacity','0').load(function() {
$(this).animate({
opacity: 1
}, 500);
});
});
</script>
<img src='yourimage.jpg' id='img'/>
If the image is an img
element:
<img src="bg.jpg" id="img" onload="this.style.opacity='1'" />
<script>document.getElementById("img").style.opacity="0";</script>
That should load the image normally if Javascript is disabled, but show it only once it loads assuming it's enabled.
One thing to note (that I overlooked); some browsers will not even attempt to load an image if its display
property is none
. That's why this method uses the opacity
attribute.
这篇关于只有在完全加载后才加载背景图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!