使用jQuery实现背景颜色动画效果

3

大家好,我想要用jQuery来实现按钮背景色的动画效果。

$(document).ready(function(){
    $('button').mouseenter(function(){
        $('button').animate({
            background-color:"blue"},1000);
    });
    $('button').mouseleave(function() {
        $('button').animate({
            background-color:"white"},1000);
    });
});

我做错了什么?还有一件事,你能够用通俗易懂的语言解释一下吗? :D
附注:我正在使用bootstrap
2个回答

6

jQuery无法原生地动画化颜色。您需要使用插件,例如此插件:http://www.bitstorm.org/jquery/color-animation/

更好的方式是使用CSS过渡,假设您不需要支持IE9或更低版本。

button {
  background-color: blue;
  transition: background-color 1s;
  -moz-transition: background-color 1s;
  -webkit-transition: background-color 1s;
  /* for prettyness only */
  border: 0;
  color: #CCC;
  border-radius: 5px;
  padding: 10px;
}
button:hover {
  background-color: white;
}
button a {
  color: white;
  transition: color 1s;
  -moz-transition: color 1s;
  -webkit-transition: color 1s;
}
button:hover a {
  color: blue;
}
<button><a href="#">Foo bar</a>
</button>


太好了!它起作用了!我还有一件事要问你。我如何使文本颜色也动画化?我在<button>中嵌套了一个<a>。我尝试对a(a:hover也是)做完全相同的事情,但文本不会动画化...我使用了transition:color 0.5s;和a:hover{ color:black; }最初它是绿色的。 - the_young_programmer
同样的技巧也适用于那个问题;我已经为你更新了我的示例。 - Rory McCrossan

1

jQuery本身不支持此功能。尝试使用jQuery.color插件:

<script type="text/javascript" src="http://code.jquery.com/color/jquery.color-2.1.2.min.js"></script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接