Updating animation-duration in Javascript

后端 未结 3 1642
梦毁少年i
梦毁少年i 2021-01-21 00:54

After changing the animation-duration (or in this case, -webkit-animation-duration) property via JavaScript with setProperty(\"-webkit-animation-

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-21 01:14

    It's not easy to restart CSS animation or change its parameter. However, I found some trick. See the following code. I separated the animation parameters into the class, which I add / remove. Plus the trick found in CSS-Tricks article and it works:

    $(document).ready(function() {
      $('#slow-btn').click(function(){
        $('#testdiv').removeClass("testanimation");
        $('#testdiv').css("-webkit-animation-duration", "5s");
        $('#testdiv').get(0).offsetWidth = $('#testdiv').get(0).offsetWidth;
        $('#testdiv').addClass("testanimation");
      });
      $('#fast-btn').click(function(){
        $('#testdiv').removeClass("testanimation");
        $('#testdiv').css("-webkit-animation-duration", "1s");
        $('#testdiv').get(0).offsetWidth = $('#testdiv').get(0).offsetWidth;
        $('#testdiv').addClass("testanimation");
      });
    });
    #testdiv {
        display: block;
        position: absolute;
        left: 100px;
        width: 100px;
        height: 100px;
        background: red;
    }
    .testanimation {
        -webkit-animation: myanimation 2s linear alternate infinite;
        animation: myanimation 2s linear alternate infinite;
    }
    @-webkit-keyframes myanimation {
        from {left: 100px;}
        to {left: 400px;}
    }
    @keyframes myanimation {
        from {left: 100px;}
        to {left: 400px;}
    }
    
    

提交回复
热议问题