如何使用 jQuery 动画更改背景图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4630947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I change the background image using jQuery animation?
提问by getaway
I want to change the background image using slow animation, but its not working
我想使用慢速动画更改背景图像,但它不起作用
$('body').stop().animate({background:'url(1.jpg)'},'slow');
Is there something wrong with the syntax!!
是不是语法有问题!!
回答by Marcus Whybrow
You can get a similar effect by fading the image opacity to 0, then change the background image, and finally fading the image back in again.
您可以通过将图像不透明度淡化为 0,然后更改背景图像,最后再次将图像淡入淡出来获得类似的效果。
This will require a div, behind everything else on your page which is as wide as the body.
这将需要一个 div,在页面上与正文一样宽的所有其他内容之后。
<body>
<div id="bg"></div>
...
</body>
You can make it as wide as the page using CSS:
您可以使用 CSS 使其与页面一样宽:
#bg {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
And then animate it's properties.
然后动画它的属性。
$('#bg')
.animate({opacity: 0}, 'slow', function() {
$(this)
.css({'background-image': 'url(1.jpg)'})
.animate({opacity: 1});
});
You could get more of a crossover effect, by having a second background div on top of this one, which you can then fade in.
通过在这个背景 div 之上放置第二个背景 div,您可以获得更多的交叉效果,然后您可以淡入。
回答by ?ime Vidas
From the jQuery documentation:
来自 jQuery 文档:
properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.)
非数字属性不能使用基本的 jQuery 功能进行动画处理。(例如,宽度、高度或左侧可以设置动画,但背景颜色不能。)
Source: http://api.jquery.com/animate/
回答by user113716
You can't animate the adding/replacing of a background image. The URL is either there or not. There's no in between state.
您不能为背景图像的添加/替换设置动画。URL 要么存在,要么不存在。没有中间状态。
回答by diagonalbatman
The way to achieve this may be to onclick add a new class with the background image in. Then animate this? Or fade out the image to reveal a new one?
实现这一点的方法可能是 onclick 添加一个带有背景图像的新类。然后设置动画?或者淡出图像以显示新图像?
回答by Chandu
I would use a faux div to cover the background as a fixed element and then animate that element i.e:
我会使用人造 div 作为固定元素覆盖背景,然后为该元素设置动画,即:
<div id="bgDiv" style='display:none;background:URL("Water lilies.jpg");position:fixed; width: 100%; height: 100%; z-index: -1'></div>
<script type="text/javascript">
$(document).ready(function(){
$('#bgDiv').toggle(1000); //You can plugin animate function here.
});
</script>
回答by yPhil
Here is how I did it:
这是我如何做到的:
$(this).animate({
opacity: 0
}, 100, function() {
// Callback
$(this).css("background-image", "url(" + new_img + ")").promise().done(function(){
// Callback of the callback :)
$(this).animate({
opacity: 1
}, 600)
});
});