我有以下导航
<nav>
<a href="#" class="current">HOME</a>
<a href="#">ABOUT</a><a href="#">CONTACT</a>
</nav>
采用这种样式:
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;
}
并希望将 mouseover
上的 BG 颜色设置为 #585858
并在 mouseleave
之后返回到 #a3a3a3
以及要再次删除的样式属性。
我试过这段代码,但样式属性在 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');
});
});
那么在动画结束后去掉style属性需要做哪些改动呢?
最佳答案
您在这里遗漏了一个事实,即 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') }
});
关于jQuery .removeAttr ('style' ) 在 .animate() 之后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14374703/