繁体   English   中英

背景颜色不变吗?

[英]background-color not changing?

因此,它将更改背景图像,但不会更改背景颜色。 无论如何要指出我的代码中的问题?

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

盲目猜测:

您需要在将事件绑定到节点之前确保节点存在于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或未将[id="menu"] a元素嵌套在另一个元素下。

如上所述,如果您仅添加以下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来支持它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM