背景颜色不变

background-color not changing?

本文关键字:颜色 背景      更新时间:2023-09-26

因此它会更改背景图像,但不会更改背景颜色。不管怎样,想指出我代码中的问题吗?

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;
}

如上所述。。。如果你只添加下面的css,它就会处理好它。

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

:hover是一个伪css类,您可以在任何事情上使用它,而无需添加jquery/js来支持它。

黑暗中的镜头:

在将事件绑定到DOM之前,需要确保这些节点存在于DOM中。如果您在<head>中呼叫<script>,请等待document.ready:

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

或者,您可以通过在其他地方使用具有更高特异性的选择器来覆盖background-color属性。如果您定义了a:linka:visiteda:hovera:focusa:active等样式,则需要一个更高特异性的选择器来覆盖它:

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

您需要为我们提供更多的CSS,以便为您提供更好的建议。


您可能拼错了ID,或者没有将a元素嵌套在另一个具有[id="menu"]的元素下。

根据ShankarSangoli的评论,你的css中可能有另一条规则覆盖了背景颜色,这反过来可能是一个特定的问题。

您可以通过稍微更改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', '');
    }
);

您的问题是某些内容覆盖了您的背景颜色。使用firebug或其他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;
}