【问题标题】:add css transition time to toggle class using javascript添加 css 转换时间以使用 javascript 切换类
【发布时间】:2013-11-20 15:09:46
【问题描述】:

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

任何帮助将不胜感激

【问题讨论】:

    标签: javascript html css toggle transition


    【解决方案1】:

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

    .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

    【讨论】:

      【解决方案2】:

      在你的 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

      【讨论】:

        猜你喜欢
        • 2021-07-23
        • 1970-01-01
        • 2015-11-30
        • 2014-11-23
        • 1970-01-01
        • 2014-02-04
        • 2021-12-07
        • 2022-01-21
        • 2021-10-22
        相关资源
        最近更新 更多