Home > Web Front-end > JS Tutorial > How to solve the problem of invalid hover in js

How to solve the problem of invalid hover in js

零下一度
Release: 2017-06-25 09:24:05
Original
2461 people have browsed it

This is actually caused by the priority of css.

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>
Copy after login
#add{
  width: 50px;
  height: 50px;
  background-color: greenyellow;
}#add:hover{
  background-color: #000;
}
Copy after login

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";
Copy after login

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;
}
Copy after login

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.

So what should we do?

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template