添加CSS转换时间以使用javascript切换类

use*_*766 2 html javascript css transition toggle

我想为我的纯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>
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

PSL*_*PSL 6

尝试在目标类本身中添加过渡规则。

.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;

}
Run Code Online (Sandbox Code Playgroud)

演示版

或者只是将规则应用到单独的规则中:

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;
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="div" class="class1 transition">click here</div>
Run Code Online (Sandbox Code Playgroud)

演示版