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

时间:2013-11-20 15:09:47

标签: javascript html css toggle transition

我想在我的纯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>

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:5)

尝试在目标类本身中添加转换规则。

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

}

<强> Demo

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

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:

<div id="div" class="class1 transition">click here</div>

<强> Demo

答案 1 :(得分:0)

在CSS上添加转换

#div{
    width: 200px;
    height: 150px;
    -webkit-transition: all .5s ease-in-out;
    -moz-transition: all .5s ease-in-out;
    -ms-transition: all .5s ease-in-out;
    -o-transition: all .5s ease-in-out;
    transition: all .5s ease-in-out;
}

DEMO