简体   繁体   中英

:hover not working on <li> after backgroundColor change

I have managed to get a <ul> to switch display on and off with only a few lines of vanilla JavaScript code but I've run into an issue.

I gave the <li> that switches it on/off a :hover value (gray in this case). I'm keeping the same color on the <li> as the <ul> is collapsed. When the <ul> display is turned off though, I return it to the same value as it had had previously but the :hover value no longer works. Any solutions to this?

This is my JavaScript:

function expandIt(obj) {
    obj.nextSibling.style.display = "block";
    obj.style.backgroundColor = "gray";};

function reduceIt(obj) {
    obj.style.display = "none";
    obj.previousSibling.style.backgroundColor = "white";};

This is the HTML:

<ul>
    <li onclick="expandIt(this)">ITEM</li>
        <ul onclick="reduceIt(this)">
            <li>subitem</li>
        </ul>
</ul>

hover versus inline style

The solution would be to add or a remove a class name with the styling you want. Due to css specificity, anything directly placed in style is going to take precedence over the defined rule inside of your css hover definition. The result is that your hover is never going to register the change of background color.

issues with siblings

Another issue with your code is that nextSibling and previousSibling are going to examine text nodes as well as elements. The trick there is going to be to ensure you are looking at an actual element and not a text node.

Something like this approach will ensure you end up with an element ( .nodeType == 1 )

function expandIt(obj) {
 var next = obj.nextSibling;
 while(next && next.nodeType != 1)next = next.nextSibling;
 next.style.display = "block";
 obj.style.backgroundColor = "gray";
};

function reduceIt(obj) {
 obj.style.display = "none";
 var prev = obj.previousSibling;
 while(prev && prev.nodeType != 1)prev = prev.previousSibling;
 prev.style.backgroundColor = "white";
};

Here is a demo of that concept: http://jsfiddle.net/Yu97H/

Now, even with that working example, it is possible to click so that gray is set as the background, but have hover broken. A simple rule such as ul li:hover { background-color: blue; } ul li:hover { background-color: blue; } will exhibit that behavior.

Here is a demo of that behavior: http://jsfiddle.net/Yu97H/1/

You could get this working with the !important modifier in your css. Something like this:

ul li:hover {
   background-color:#ccc !important;
}

This overrides inline styles

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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