回到相同的颜色

时间:2014-08-01 19:56:22

标签: jquery css animation

$(".color").hover(function(){
$(this).animate({ backgroundColor: 'red' });
},function(){
$(this).animate({ backgroundColor: '' });
});

我想为不同div的背景颜色设置动画。 当鼠标离开div时,是否可以使用原始颜色?

3 个答案:

答案 0 :(得分:3)

您需要在更换之前将BG颜色保存到元素中。在这里,我将其保存在数据属性中:

$(".color").hover(function(){
    var $this = $(this);
    $this.data('bg-color', $this.css('backgroundColor'));
    $this.animate({ backgroundColor: 'red' });
},function(){
    var $this = $(this);
    $(this).animate({ backgroundColor: $this.data('bg-color') });
});

http://jsfiddle.net/gunderson/9AAGJ/1/

答案 1 :(得分:1)

你可以通过css

来完成

<强> DEMO

.pink:hover, .cyan:hover, .green:hover {
    background-color:red;
    transition: all 1s;
}

答案 2 :(得分:0)

你可以这样做:

(function () 
    var original;
    $(".color").hover(function () {
        original = $(this).css('background-color');
        $(this).animate({
            backgroundColor: 'red'
        });
    }, function () {
        $(this).animate({
            backgroundColor: original
        });
    });
());

该函数包装器用于防止创建全局原始变量,如果需要,可以将其删除。

相关问题