简体   繁体   English

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

[英]add css transition time to toggle class using javascript

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 任何帮助,将不胜感激

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;

}

Demo 演示

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>

Demo 演示

Add transition on your CSS 在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 DEMO

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

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