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

标签 jquery html

我有以下导航

<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/

相关文章:

html - 如何在 Chrome 中滚动隐藏数据列表?

javascript - 下拉列表应在提交表单时显示所选值

html - 为什么设置边距会删除列表缩进

jquery - 选择最后动态添加的文本框

javascript - csv 到具有自定义属性的响应表

javascript - Globalize.js - cldr.once 不是函数

javascript - 在 JSFiddle 中工作,即使放置在文档就绪处理程序中也不能在浏览器中工作

javascript - 自定义 Jquery UI 日期选择器

javascript - 明确设置 scrollTop 时 iOS webkit 浏览器上的无限滚动闪烁

html - 如何清除 Bootstrap 3 中的 float ?