#add{ width: 50px; height: 50px; background-color: greenyellow; } #add:hover{ background-color: #000; } Left"/> #add{ width: 50px; height: 50px; background-color: greenyellow; } #add:hover{ background-color: #000; } Left">
Home > Article > Web Front-end > How to solve the problem of invalid hover in js
First let’s take a look at how hover can set the background color normally without adding css attributes using js.
<div id="add"></div>
#add{ width: 50px; height: 50px; background-color: greenyellow; }#add:hover{ background-color: #000; }
The picture on the left is by default, and the picture on the right is when the mouse is placed on it, now hover It can still be displayed normally.
(The pictures below are all default on the left and hover on the right. It should be because the screenshot tool cannot capture the mouse)
But if the css style is inserted through js, the hover style will be used when the mouse is placed. It won't take effect.
var add = document.getElementById("add"); add.style.backgroundColor = "red";
The #000 attribute set in hover is now invalid.
But this is not the function that the hover pseudo-class has lost. If the setting is not a style added by js, you can see that hover is not invalid. For example, try adding a font color.
#add:hover{ background-color: #000; color: yellow; }
You can see that the font color will still change.
The reason is that the css style should be added to js directly on the style of the html tag, and the priority of style is higher than the css pseudo-class.
From top to bottom style, hover, id selector.
You can see in the browser debugging tool that js is added directly to the style.
It talks about the priority of the selector. But it did not talk about the priority of css pseudo-classes and styles.
But: the hover pseudo-class is also invalid. Description style>css pseudo-class>id>class.
Just add !important after the :hover attribute. Should be !important priority above all else! !
!important>style>css pseudo-class>id>class.
#add:hover{ background-color: #000 !important; }
Now I finally achieved the desired result.
The above is the detailed content of How to solve the problem of invalid hover in js. For more information, please follow other related articles on the PHP Chinese website!