【问题标题】:How to change background color on condition如何根据条件更改背景颜色
【发布时间】:2016-08-22 12:43:56
【问题描述】:

我正在使用以下样式在我的页面中将 div 显示为偶数组合: css:

.task-container:nth-child(even) {
    background: none;
}

.task-container:nth-child(odd) {
    background: rgba(2, 104, 144, .05);
}

.timeout {
    background-color: #ffc;
}

在 HTML 中。我在ng-repeat 中使用div

<div class="task-container">
    ... other divs
</div>

在某些情况下,我想将背景颜色更改为黄色,但它不能作为 nth-child(even)/odd 覆盖黄色。我尝试了类似的方法:

<div class="task-container" data-ng-class="{'timeout': alarm.timeOutOccured== true}">

有人可以帮我找到正确的方法吗?

【问题讨论】:

    标签: javascript angularjs css


    【解决方案1】:

    假设.timeout 类已正确添加到您的div 元素上,您只需在您的CSS 中添加!important

    .timeout {
        background-color: #ffc !important;
    }
    

    这是因为,.task-container:nth-child(even).task-container:nth-child(odd) 更具体,因此将获得更高的优先级。

    另外,不建议使用!important,所以你可以像这样写更具体的选择器(你不需要!important标志):

    .task-container.timeout {
        background-color: #ffc;
    }
    

    请看下面的简化示例:

    .task-container:nth-child(even) {
      background: none;
    }
    .task-container:nth-child(odd) {
      background: rgba(2, 104, 144, .05);
    }
    .task-container.timeout {
      background-color: #ffc;
    }
    <div class="task-container">
    1
    </div>
    <div class="task-container">
    2
    </div>
    <div class="task-container timeout">
    3
    </div>
    <div class="task-container">
    4
    </div>
    <div class="task-container">
    5
    </div>
    <div class="task-container">
    6
    </div>
    <div class="task-container timeout">
    7
    </div>

    【讨论】:

    • 添加一个更具体的类怎么样?我不建议使用 !important,它只能被另一个 !important css 样式覆盖
    • 谢谢@Max 我刚刚更新了
    • 更具体的意思是:task-container.is-timeout { background-color: #ffc }
    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 2013-10-24
    相关资源
    最近更新 更多