1

原始的jQuery:

$('#container section').each(function() {
                $(this).waypoint(function(direction) {
                    var anchorRef = 'a[href="#' + this.id + '"]';
                    if (direction === 'down') {
                        $(anchorRef).animate({'backgroundColor' : 'rgb(230, 77, 78)'});
                    } else {
                        $(anchorRef).animate({'backgroundColor' : 'rgb(25, 25, 25)'});
                    }
                });
            });

CSS:

.main-menu ul li a:hover {
    background-color: #333;
}

问题是,一旦动画结束,如果我们返回到那个元素,悬停效果就不会再应用了。

任何线索为什么?

我试图像这样在脚本上“强制”夸大其词:

$('#container section').each(function() {
                $(this).waypoint(function(direction) {
                    var anchorRef = 'a[href="#' + this.id + '"]';
                    var anchorRefHover = 'a[href="#' + this.id + '"]:hover';//NEW
                    if (direction === 'down') {
                        $(anchorRef).animate({'backgroundColor' : 'rgb(230, 77, 78)'});
                        $(anchorRefHover).css({backgroundColor : '#333'});//NEW
                    } else {
                        $(anchorRef).animate({'backgroundColor' : 'rgb(25, 25, 25)'});
                        $(anchorRefHover).css({backgroundColor : '#333'});//NEW
                    }
                });
            });

仍然失去了 CSS 上的悬停效果市场。

我在 CSS 悬停规则上添加了 !important。这会触发悬停。但是我更喜欢使用 javascript 的原因是, 悬停背景颜色应该只适用于我们悬停的元素没有背景 rgb(230, 77, 78)

不确定它是否会起作用,但我正在考虑在上述情况下通过 javascript 添加 !important ......但也许有更好的方法?

有什么线索可以帮助我吗?

注意:感谢 koala_dev efford,这是小提琴:

http://jsfiddle.net/talofo/5YgY5/5/

4

1 回答 1

3

正如@DomDay 在评论中指出的那样,jQuery.animate()使用覆盖您的 CSS 规则的内联样式,因此一种解决方案是在您将颜色恢复为原始颜色时删除内联语句,如下所示:

$(anchorRef).animate({'backgroundColor': 'rgb(25, 25, 25)'},function(){
    $(this).removeAttr('style');
});

工作小提琴

于 2013-07-27T18:26:06.813 回答