我试图在鼠标悬停时使用jQuery动画改变backgroundColor。

我检查了一些例子,我似乎有它是正确的,它与其他属性,如fontSize,但与backgroundColor我得到和“无效属性”js错误。 我正在使用的元素是div。

$(".usercontent").mouseover(function() {
    $(this).animate({ backgroundColor: "olive" }, "slow");
});

什么好主意吗?


当前回答

试着使用它

-moz-transition: background .2s linear;
-webkit-transition: background .2s linear;
-o-transition: background .2s linear;
transition: background .2s linear;

其他回答

你可以使用2个div:

你可以在上面放一个复制品,然后在把复制品淡入的同时把原来的淡出。

当淡出完成后,用新的bg恢复原始。

$(function(){
    var $mytd = $('#mytd'), $elie = $mytd.clone(), os = $mytd.offset();

      // Create clone w other bg and position it on original
    $elie.toggleClass("class1, class2").appendTo("body")
         .offset({top: os.top, left: os.left}).hide();

    $mytd.mouseover(function() {            
          // Fade original
        $mytd.fadeOut(3000, function() {
            $mytd.toggleClass("class1, class2").show();
            $elie.toggleClass("class1, class2").hide();            
        });
          // Show clone at same time
        $elie.fadeIn(3000);
    });
});​

jsFiddle例子

.toggleClass() .offset() .fadeIn() .淡出()

我喜欢使用delay()来完成这个任务,这里有一个例子:

jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);

这可以由函数调用,“element”是元素类/名称/等。元素将立即以#FCFCD8背景出现,稍等片刻,然后淡出为#EFEAEA。

如果有人发现了这个。你最好使用jQuery UI版本,因为它可以在所有浏览器上运行。颜色插件在Safari和Chrome浏览器中存在问题。只是有时候有用。

试试这个:

jQuery(".usercontent").hover(function() {
    jQuery(this).animate({backgroundColor:"pink"}, "slow");
},function(){
    jQuery(this).animate({backgroundColor:"white"}, "slow");
});

修订后的效果:

jQuery(".usercontent").hover(function() {

    jQuery(this).fadeout("slow",function(){
        jQuery(this).animate({"color","yellow"}, "slow");
    });
});

如果你不想只使用jQuery核心功能来动画你的背景,试试这个:

jQuery(".usercontent").mouseover(function() {
      jQuery(".usercontent").animate({backgroundColor:'red'}, 'fast', 'linear', function() {
            jQuery(this).animate({
                backgroundColor: 'white'
            }, 'normal', 'linear', function() {
                jQuery(this).css({'background':'none', backgroundColor : ''});
            });
        });