添加 css 转换时间以使用 javascript 切换类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20099577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add css transition time to toggle class using javascript
提问by user2906766
I want to add a transition time to my pure javascript toggle class function I knew how to code it but i forgot and now need some advice
我想为我的纯 javascript 切换类函数添加一个过渡时间我知道如何编写它,但我忘记了,现在需要一些建议
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#div{
width: 200px;
height: 150px;
}
.class1 {
color: #f00;
background-color: #2fadac;
}
.class2 {
color: #00f;
background-color: #c33;
}
</style>
</head>
<body>
<div id="div" class="class1">click here</div>
<script>
function classToggle() {
this.classList.toggle('class1');
this.classList.toggle('class2');
style.cssText ="-webkit-transition: all 0.5s ease-in-out;";
}
document.querySelector('#div').addEventListener('click', classToggle);
</script>
</body>
</html>
any help would be appreciated
任何帮助,将不胜感激
回答by PSL
Try add the rule for transition in your target class itself.
尝试在目标类本身中添加转换规则。
.class1 {
color: #f00;
background-color: #2fadac;
-webkit-transition: all 0.5s ease-in-out;
}
.class2 {
color: #00f;
background-color: #c33;
-webkit-transition: all 0.5s ease-in-out;
}
Or just apply the rule in a separate rule:
或者只是在单独的规则中应用该规则:
CSS:-
CSS:-
.class1 {
color: #f00;
background-color: #2fadac;
}
.class2 {
color: #00f;
background-color: #c33;
}
.transition{
-webkit-transition: all 0.5s ease-in-out;
-moz-transition:all 0.5s ease-in-out;
-o-transition:all 0.5s ease-in-out;
transition:all 0.5s ease-in-out;
}
HTML:
HTML:
<div id="div" class="class1 transition">click here</div>