Is there a feasible way to trigger CSS keyframe animation using JS?

前端 未结 3 1552
谎友^
谎友^ 2021-01-18 07:58

Naturally, we can create a CSS animation using keyframes, and control it from there.

However, ideally, I would like to trigger this animation from a button click - s

3条回答
  •  既然无缘
    2021-01-18 08:03

    see here jsfiddle

    if you want your animation to work every time you press the button use this code :

    $('button').click(function() {
        $(".fademe").addClass('animated');
        setTimeout(function() {
          $(".fademe").removeClass('animated');
        }, 1500);
    });
    

    where 1500 is the animation-duration in this case, 1.5s

    $('button').click(function() {
      $(".fademe").addClass('animated');
      setTimeout(function() {
        $(".fademe").removeClass('animated');
      }, 1500);
    });
    .fademe {
      width: 100px;
      height: 100px;
      background: red;
    }
    
    .fademe.animated {
      animation: fade-in 1.5s ease;
    }
    
    
    @keyframes fade-in {
      0% {
        opacity: 0;
      }
    
      100% {
        opacity: 1;
      }
    }
    
    

    EXPLANATION :

    1. on click on the button add class animated ( or any other class ) to the element you want to apply the animation to , .fademe
    2. make a setTimeout(function() to delay the removeClass for the duration of the animation 1.5s or 1500ms
    3. write in CSS the declaration of the animation , @keyframes, and add it to the element with the class added by the JQ .fademe.animated

提交回复
热议问题