2012-02-07 142 views
1

所以它改变背景图像,但不改变背景颜色。 无论如何照顾指出我的代码中的问题?背景颜色不变?

的JavaScript:

$("#menu a").hover(function() { 
    $(this).addClass("hover"); 
}, function() { 
    $(this).removeClass("hover"); 
}); 

CSS:

.hover { 
    background-color: white; 
    background-position: top center; 
    background-image: url("img/dot.png"); 
    background-repeat: no-repeat; 
    color: red; 
} 
+0

你需要显示非悬停默认类。 – 2012-02-07 14:57:42

+2

也许是其他的CSS规则重写它在页面上。 – ShankarSangoli 2012-02-07 14:57:51

+6

你不必使用'$ .hover()';您可以使用':hover'伪类在纯CSS中执行此操作。 – Bojangles 2012-02-07 14:58:11

回答

0

如上所述......如果你只是添加下面的CSS,它会照顾它。

a:hover { 
    background-color: white; 
    background-position: top center; 
    background-image: url("img/dot.png"); 
    background-repeat: no-repeat; 
    color: red; 
} 

:悬停是一个伪CSS类,你可以用它在任何东西,而不需要添加的jQuery/JS来支持它。

0

一个瞎猜:

你需要确保的是,在DOM中存在的节点事件绑定到他们面前。如果你在等待<head>拨打您<script>document.ready

jQuery(function($){ 
    $("#menu a").hover(function() { 
     $(this).addClass("hover"); 
    }, function() { 
     $(this).removeClass("hover"); 
    }); 
}); 

或者,你可以通过选择具有higher specificity其他地方重写background-color财产。如果你定义的样式,如a:linka:visiteda:hovera:focus,或a:active则需要更高的特异性选择重写它:

a.hover { 
    /* your styles here */ 
} 

你需要提供更多的CSS的我们给你更好的建议。


您可能拼错一个ID或者以另一个元素与[id="menu"]没有嵌套的a元素。

0

根据ShankarSangoli的评论,你可能在你的css中有另一个规则覆盖背景颜色,而这又可能是specificity的问题。

您可以通过稍微改变你的hover功能测试:

$("#menu a").hover(
    function() { 
     //add 'background-color' as an inline css style which will have higher specificity than anything in the css. 
     $(this).addClass("hover").css('background-color', 'white'); 
    }, function() { 
     $(this).removeClass("hover").css('background-color', ''); 
    } 
); 
0

您的问题是什么覆盖您的背景颜色。使用萤火虫或其他DOM检查员来查找您的问题。修补程序,让您的背景颜色很重要,但你应该只使用这个来进行测试:

background-color: black !important; 

如果一切正常,你仍然需要找出什么是覆盖你的背景。

然后你可以用纯CSS做

#menu a:hover { 
    background-color: black; 
    background-position: top center; 
    background-image: url("img/dot_hover.png"); 
    background-repeat: no-repeat; 
    color: red; 
}