Setting background color with JavaScript breaks the CSS hover behavior

前端 未结 4 1343
你的背包
你的背包 2021-01-15 14:47

I\'m trying to create a menu where the currently selected (clicked) element has a different background color than the other elements (I\'m trying to achieve this using JavaS

相关标签:
4条回答
  • 2021-01-15 15:14

    you need to use !important on hover, basically it will increase its priority.

    Try this,

    p#links a:hover {
        background-color: #f00 !important;
    }
    

    DEMO


    As Quentin said it looks like a dirty one, so in that situation we can make use of the class priority concepts.

    HTML:

    <a class='normal' href="#">Link 1</a>
    <a class='normal' href="#">Link 1</a>
    

    CSS:

    .normal { background-color: blue; } 
    .abnormal{ background-color: yellow; }
    
    .normal:hover { background-color: #f00; }
    

    JS:

    $('p#links a').attr('class', 'abnormal normal');
    

    DEMO Non-Dirty one

    0 讨论(0)
  • 2021-01-15 15:22

    How about keeping the style in CSS and not in Javascript, by adding classes ?

    so the line :

    elements[i].style.backgroundColor = '#ff0';
    

    Change to

    elements[i].className = 'myClassForBackgrounds';
    

    or in the jQ version

    $('p#links a').css('background-color', '#ff0');
    

    to :

    $('p#links a').addClass('myClassForBackgrounds');
    

    That way you can set your :hover as you would normally

    #links a:hover, .myClassForBackgrounds:hover { background-color:#ff0; }
    
    0 讨论(0)
  • 2021-01-15 15:23

    The jQuery css() method maps onto the style property which maps onto the style attribute.

    Rules inside a style attribute are more specific then rules in a stylesheet, so will always come after them in the cascade.

    Instead of altering the CSS on the element directly, alter it by changing the classes the element belongs to and having a pre-prepared stylesheet.

    0 讨论(0)
  • 2021-01-15 15:24

    Just for a more simple answer, in able to just re-enable css rules just have it toggle between the color and "", so

    document.getElementById("id").style.backgroundColor = "rgb(255, 125, 15)";
    

    would be if the element wasn't already colored via javascript. Now, if your element was already colored the code would look like this:

    document.getElementById("id").style.backgroundColor = "";
    

    That re-enables CSS so then your selectors will work.

    0 讨论(0)
提交回复
热议问题