简体   繁体   English

JavaScript和CSS类未按预期运行

[英]JavaScript and CSS classes not acting as expected

I have set up a custom navigation bar which when I am scrolling through a website slides the current nav which is occupying the majority of the screen out slightly. 我已经设置了一个自定义导航栏,当我在网站上滚动时,它会略微占据当前大部分屏幕的当前nav

Example extracts from the CSS and JS are as follows CSS和JS的示例摘录如下

/*CSS*/
#topnav {
    top: 100px;
    background-color:white;
    border-top-style:solid;
}

.topActive {
    z-index:5000;
    width:3cm;
    background-color:black;
    border-style:solid;
    border-right-style:none;
    color:white;
}

/*JS*/
if(nav == 0) {
    $("#topnav").addClass("topActive topnavb");
    ...

In this example, I would expect that when the nav tab in the nav bar slides out the background colour of it is black; 在此示例中,我希望当导航栏中的导航选项卡滑出时,其背景颜色为黑色; however, in this case, the background colour would be white still. 但是,在这种情况下,背景颜色仍为白色。 Essentially the class is not overriding the properties in the id 本质上, class不会覆盖id的属性

I would appreciate any help in fixing this problem 对于解决此问题,我将不胜感激

It is because of the CSS specificity . 这是因为CSS的特殊性 From the link: 从链接:

The following list of selector types is by increasing specificity: 以下选择器类型列表是通过提高特异性来实现的:

  • Type selectors (eg, h1) and pseudo-elements (eg, :before). 类型选择器(例如h1)和伪元素(例如:before)。
  • Class selectors (eg, .example), attributes selectors (eg, [type="radio"]) and pseudo-classes (eg, :hover). 类选择器(例如.example),属性选择器(例如[type =“ radio”])和伪类(例如:hover)。
  • ID selectors (eg, #example). ID选择器(例如,#example)。

So an ID will always override a class . 因此, ID将始终覆盖class

The css specificity of a class is lower than that of an id. 类的CSS特异性低于ID的CSS特异性。 This causes id rules to override class rules. 这将导致id规则覆盖类规则。

https://css-tricks.com/specifics-on-css-specificity/ https://css-tricks.com/specifics-on-css-specificity/

After reading up on specificity which the other answers have been talking about I found a command which can be added to the end of the line. 在阅读了其他答案一直在谈论的specificity ,我找到了可以添加到该行末尾的命令。 This is !important . 这很!important Even though !important is normally considered bad practice, see here for more about the practice of using !important , in this case it is not considered bad practice. 即使!important通常被认为是不好的做法,但请参阅此处以了解更多有关使用!important的实践,在这种情况下,它不被认为是不好的做法。 This is because it is overriding one property which is otherwise unchanged in any further use of style sheets in this website. 这是因为它覆盖了一个属性,否则该属性在此网站上对样式表的任何进一步使用中都不会更改。

Browsers will choose the property that is defined in the more precise rule. 浏览器将选择更精确的规则中定义的属性。 Id selectors are more precise than class selectors. ID选择器比类选择器更精确。 You juste have to use #topnav.topActive instead of .topActive 您只需要使用#topnav.topActive而不是.topActive

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

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