jQuery animate不适用于background-image

问题描述 投票:-1回答:5

我想使用jQuery的动画更改容器的背景图像。我试过这个,但它不起作用,没有编译错误:

$("#main-container").animate(
{"background-image": 'url("images/background2.png")'},2000);

我可以用css做,但我想要动画效果。

$("#main-container").css(
{"background-image": 'url("images/background2.png")'});

知道为什么会这样吗?

jquery css jquery-animate
5个回答
0
投票

HTML:

<div id="main-container"></div>

CSS:

 #main-container{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

JQuery的:

$('#main-container')
    .animate({opacity: 0}, 'slow', function() {
        $(this)
            .css({'background-image': 'url(images/background2.png)'})
            .animate({opacity: 1});
    });

如需进一步参考,请参阅以下链接。

How do I change the background image using jQuery animation?


0
投票

您可以使用CSS转换:

CSS:

#bgDiv {
    width: 250px; 
    height: 250px;
    /* For Safari 3.1 to 6.0 */
    -webkit-transition-property:background-image;
    -webkit-transition-duration:1s;
    -webkit-transition-timing-function:linear;
    -webkit-transition-delay:0s;
    /* Standard syntax */
    transition-property: background-image;
    transition-duration: 1s;
    transition-timing-function: linear;
    transition-delay: 0s;
}

.background1 {
    background-image: url("http://lorempixel.com/output/abstract-q-c-250-250-5.jpg");
}

.background2 {
    background-image: url("http://lorempixel.com/output/nature-q-c-250-250-7.jpg");
}

HTML:

<script>
    function backgroundChange(){
    $("#bgDiv").removeClass("background1").addClass("background2");
    };
</script>
<p onclick="backgroundChange()">Click Me</p>
<div id="bgDiv" class="background1"></div>

我为你创建了一个样本:http://jsfiddle.net/CjL7r/


0
投票

你不能使用jQuery的动画与图像 - 它只是不起作用.Reference

但是获得解决方案的方法.Reference

A working demo

setTimeout(animate, 2000);

function animate() {
    $('#main-container').animate({}, 'fast', function () {
        $(this).css({
            'background-image': 'url(http://i.stack.imgur.com/7YKUD.jpg)'
        });
    });
}

0
投票

jQuery中没有background-image的动画(我不确定UI),但你可以通过css转换实现这种效果。尝试使用2秒轻松过渡,它应该在元素的每个更改中应用此效果(不要忘记crossbrowser问题)

http://www.w3schools.com/css/css3_transitions.asp

您还可以实现淡出动画,更改图像然后为淡入淡出动画

$("#main-container").animate({opacity: 0}, 1000, function(){
$(this).css({"background-image": 'url("images/background2.png")').animate({opacity:1},{duration:1000})
});

0
投票

使用jQuery插件进行颜色处理和动画支持:https://github.com/jquery/jquery-color

如果没有这个插件,animate()上的jQuery backgroundColor方法将无法正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.