最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CSS hover on classList - Stack Overflow

programmeradmin1浏览0评论

I have elements with class .tab and hover for them:

.tab:hover {
    background-color: #A9E59E;
}

Now, I'm adding additional class to some of those element in JS:

this.classList.toggle('tab2');

the problem is, I do not wan't hover to fire on those elements with two classes
classList.length > 1.
Is there a way in CSS to exclude those elements with two classes, so that hover fires only on .tab class, and not on .tab .tab2
or I need to move all hover logic to JS?

I have elements with class .tab and hover for them:

.tab:hover {
    background-color: #A9E59E;
}

Now, I'm adding additional class to some of those element in JS:

this.classList.toggle('tab2');

the problem is, I do not wan't hover to fire on those elements with two classes
classList.length > 1.
Is there a way in CSS to exclude those elements with two classes, so that hover fires only on .tab class, and not on .tab .tab2
or I need to move all hover logic to JS?

Share Improve this question asked Jun 16, 2015 at 12:58 Wolf WarWolf War 1,5633 gold badges15 silver badges29 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 4

If you can use CSS3 the :not selector can help you achieve what you are after:

.tab:not(.tab2):hover {
    background-color: #A9E59E;
}

Otherwise, you will have to define a new rule for elements having both classes in order to reset the background-color:

.tab:hover {
    background-color: #A9E59E;
}
.tab.tab2:hover {
    background-color: white; (or whatever your initial background color was)
}

Have you looked at the :not selector?

You can try something like this:

.tab:not(.tab2):hover {
    background-color: #A9E59E;
}

Try this syntax.

    [class="tab"]:hover{
background-color: #A9E59E;
}

Which will select the class tab ,if it has other class attributes it wont get selected.

You can add another explicit rule for the 2 classes

.tab.tab2:hover {
  background-color: #someothercolor;
}

I would do something like this:

.tab.tab2:hover{
/*apply the same style as for the non hover element */
}

We can remove hover effects using

$(element).removeClass('hover');

So while toggling classes we also can toggle hover

element.classList.toggle("tab2");
element.classList.toggle("hover");
发布评论

评论列表(0)

  1. 暂无评论