简体   繁体   English

使用CSS类切换背景色

[英]Switching background-color using css classes

I have a element that has its background color set to "lightGreen" by default and upon hovering, im adding a class that should overwrite the background-color to "red". 我有一个元素,其背景颜色默认情况下设置为“ lightGreen”,并且在悬停时,我添加了一个应将background-color覆盖为“ red”的类。

When the class gets added (and it does), its not applying the red, but sticking with the lightGreen. 当添加类(并且确实添加了该类)时,它不应用红色,而是坚持浅绿色。

Note the element has the "disabled" class by default, but in this example I have code running .removeClass("disabled") before adding "uiHighlight". 请注意,该元素默认情况下具有“ disabled”类,但是在此示例中,我在添加“ uiHighlight”之前运行了.removeClass(“ disabled”)代码。

Why is it not working as intended for me ? 为什么它不按我的预期工作?

I have this: 我有这个:

#increaseImpulse, #decreaseImpulse, #undoLastAction {
    border: 1px solid black;
    background-color: lightGreen;
}

.uiHighlight {
    background-color: red;
}

.disabled {
     display: none;
}

and this 和这个

            <tr id="undoLastAction" class="disabled">
                <td colspan=2>
                    Undo last action
                </td>
            </tr>

and this 和这个

    $("#undoLastAction")
    .hover(
        function(e){
            $(this).addClass("uiHighlight");
        },
        function(e){
            $(this).removeClass("uiHighlight");
        }
    )
    .click(function(e){
        console.log("undoLastAction")
    });

You don't really need jQuery - this can be accomplished in pure CSS: 您实际上并不需要jQuery-这可以在纯CSS中完成:

#undoLastAction {
    background-color: green;
}

#undoLastAction:hover {
    background-color: red;        
}

Check out this jsFiddle . 看看这个jsFiddle

An id selector has more specificity than a class selector - that is why it does not work. id选择器比class选择器更具特异性-这就是为什么它不起作用。 Try this: 尝试这个:

#undoLastAction.uiHighlight {
  background-color: red;
}

Cheers! 干杯!

 $("#undoLastAction").hover( function(e) { $(this).addClass("uiHighlight"); }, function(e) { $(this).removeClass("uiHighlight"); } ).click(function(e) { console.log("undoLastAction") }); 
 #increaseImpulse, #decreaseImpulse, #undoLastAction { border: 1px solid black; background-color: lightGreen; } #undoLastAction.uiHighlight { background-color: red; } .disabled { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr id="undoLastAction"> <td colspan=2> Undo last action </td> </tr> </table> 

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

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