我有以下导航
<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
并在#a3a3a3
之后返回mouseleave
并再次移除样式属性。
我尝试了这段代码,但样式属性仍在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属性需要做些哪些更改?
答案 0 :(得分:8)
您在这里遗漏的事实是,jQuery.animate
是异步的,因此在动画结束前调用removeAttr
。您应该使用完整的回调来调用removeAttr
。
您还需要jQuery.animate
的{{3}}插件才能为background-color
制作动画。
var $this = $(this);
$this.stop().animate({ backgroundColor: jQuery.Color("rgb(0, 72, 112)") }, {
duration: 300,
complete: function() { $this.removeAttr('style') }
});
答案 1 :(得分:0)
你需要jquery-ui插件to animate color。看一下你的代码,包括当前的jquery ui:http://jsfiddle.net/sUeBd/1/
$(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');
});
});
答案 2 :(得分:0)
您无法使用动画更改背景颜色...如果您需要,则必须使用jQuery.Color()
插件。你可以为这个
根据文件..
除非如下所述,否则应将所有动画属性设置为单个数值。大多数非数字属性无法使用基本jQuery功能进行动画处理(例如,宽度,高度或左边可以设置动画,但背景颜色不能,除非使用jQuery.Color()插件)。除非另有说明,否则属性值被视为多个像素。可以在适用的情况下指定单位em和%。
docs此处
使用ui插件答案 3 :(得分:0)
jQuery无法为颜色设置动画,但您可以像这样添加jQuery插件
<script src="http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors-min.js"></script>
答案 4 :(得分:0)
需要CSS3
,Chrome
,Safari
,Opera
或Firefox 5+
IE10
版本
nav a:not(.current) {
animation:navOut 1s forwards;
}
nav a:not(.current):hover {
animation:navOver 1s forwards;
}
@keyframes navOver {
to { background-color:#a3a3a3; }
}
@keyframes navOut {
from { background-color:#a3a3a3; }
to { background-color:#004870;}
}
答案 5 :(得分:0)
您可以使用CSS处理此事件。无需使用java脚本。
使用此
更新您的css代码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:#a3a3a3;
}
nav a {
margin-left: 7px;
}
nav a.current{
background:#585858;
color: white;
}
nav a:hover{
background:#585858;
}
检查这个小提琴 http://jsfiddle.net/uTYFC/2/