简体   繁体   English

如何避免悬停和活动的CSS规则被javascript中以编程方式完成的CSS更改所重写?

[英]How to avoid hover and active css rules to be rewritten by a css change done programmatically in javascript?

I have this code, changing the color of a button and turning it back to normal after less than a second 我有这段代码,更改按钮的颜色,并在不到一秒钟的时间内将其恢复为正常

document.getElementById("someid").style.color="#000000";
var clickAnimationIntervalId = setInterval(function({
    document.getElementById("someid").style.color="#000000";
    clearInterval(clickAnimationIntervalId);
}, 400);

Works fine, but after this code is executed, "someid" doesn't change anymore color on hover and active, like this code changed the css color, in any case. 工作正常,但是执行此代码后,“ someid”在悬停和活动时不再更改颜色,就像在任何情况下此代码更改了css的颜色一样。 How do I avoid this behaviour? 我如何避免这种行为?

This behavior is correct. 此行为是正确的。

To avoid this create a class that set the css of someid and add it also to the :hover and .active state in your css. 为了避免这种情况,请创建一个设置someid的CSS的类,并将其也添加到CSS中的:hover和.active状态。

Example: 例:

#someid.animationInterval {color:black}
#someid.animationInterval:hover,
#someid.animationInterval.active {*the same like your normal hover and active*}

Now you set animationInterval class via Javascript. 现在,您可以通过Javascript设置animationInterval类。

You can put on your css classes for hover and active the color attribute with !important. 您可以将css类放在悬停上,并使用!important激活color属性。 For example: 例如:

a:hover, a:active{
  color: #5fba7d!important;
}

This is because the JS is putting the your style to the button as inline . 这是因为JSyour style作为inline放置到按钮上。 So it over rights your default style. 因此,它超过了您的默认样式的版权。 If you want it to work you have to use !important to your style. 如果要使其正常工作,则必须对样式使用!important

button:hover{
 background-color:green !important;
}

This will do your job. 这将完成您的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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