.animate()之后的jQuery .removeAttr('style')不起作用

Joh*_*ann 2 html jquery

我有以下导航

<nav>
   <a href="#" class="current">HOME</a>
   <a href="#">ABOUT</a><a href="#">CONTACT</a>
</nav>
Run Code Online (Sandbox Code Playgroud)

这个造型:

nav a {
    font-family: monospace;
    display: inline-block;
    width: 114px;
    height: 29px;
    font-size: 14px;
    line-height: 29px;
    text-align: center;
    text-decoration: none;
    color: white;
    background-color: #004870;
}
nav a {
    margin-left: 7px;
}
nav a.current{
    background-color: #585858;
    color: white;
}
Run Code Online (Sandbox Code Playgroud)

而想要动画的背景色mouseover,以#585858和回#a3a3a3mouseleave和样式属性,以便再次取出.

我尝试了这段代码,但样式属性仍然存在mouseleave:

$(document).ready(function() {
   $('nav a:not(.current)').mouseenter(function() {
   $(this).stop().animate( {
          backgroundColor: '#585858'
   }, 300);
});
$('nav a:not(.current)').mouseleave(function() {
$(this).stop().animate( {
    backgroundColor: '#004870'
}, 300).removeAttr('style');
    });
});
Run Code Online (Sandbox Code Playgroud)

那么在动画结束后删除style属性需要做哪些更改?

tpe*_*zek 9

你在这里遗漏的事实是,这jQuery.animate是异步的,所以removeAttr在动画结束之前你就被调用了.您应该使用完整的回调来调用removeAttr.

您还需要jQuery.Color()插件jQuery.animate才能进行动画处理background-color.

var $this = $(this);
$this.stop().animate({ backgroundColor: jQuery.Color("rgb(0, 72, 112)") }, {
    duration: 300,
    complete: function() { $this.removeAttr('style') }
});
Run Code Online (Sandbox Code Playgroud)