Reiniciar la animación en CSS3: ¿hay mejor manera que eliminar el elemento?


Tengo una animación CSS3 que necesita ser reiniciada con un clic. Es una barra que muestra cuánto tiempo queda. Estoy usando la transformación de scaleY(0) para crear el efecto.

Ahora necesito reiniciar la animación restaurando la barra a scaleY(1) y dejarla ir a scaleY(0) de nuevo. Mi primer intento de establecer scaleY(1) falló porque toma los mismos 15 segundos para traerlo de vuelta a la longitud completa. Incluso si cambio la duración a 0.1 segundos, tendría que retrasar o encadenar la asignación de scaleY (0) para que la reposición de barras se complete. Se siente demasiado complicado para una tarea tan simple.

También encontré un consejo interesante para reiniciar la animación eliminando el elemento del documento y luego volviendo a insertar un clon del mismo: http://css-tricks.com/restart-css-animation /

Funciona, pero ¿hay una mejor manera de reiniciar una animación CSS? Estoy usando Prototype y Move.js , pero no estoy restringido a ellos.

Author: Leo, 2011-06-07

6 answers

Simplemente establezca la propiedad animation a través de JavaScript en "none" y luego establezca un tiempo de espera que cambie la propiedad a "", por lo que hereda de nuevo del CSS.

Demo para Webkit aquí: http://jsfiddle.net/leaverou/xK6sa / Sin embargo, tenga en cuenta que en el uso del mundo real, también debe incluir-moz- (al menos).

 50
Author: Lea Verou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-21 03:46:29

No hay necesidad en tiempo de espera, utilice reflow para aplicar el cambio:

function reset_animation() {
  var el = document.getElementById('animated');
  el.style.animation = 'none';
  el.offsetHeight; /* trigger reflow */
  el.style.animation = null; 
}
#animated {
  position: absolute;
  width: 50px; height: 50px;
  background-color: black;
  animation: bounce 3s ease-in-out infinite;
}
@keyframes bounce {
  0% { left: 0; }
  50% { left: calc( 100% - 50px ); }
  100% { left: 0; }
}
<div id="animated"></div>
<button onclick="reset_animation()">Reset</button>
 17
Author: user,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-11 14:02:34

Si tiene alguna clase para la animación css3, para exapmle .parpadeo entonces usted puede removeClass para algún elemento y addClass para este elemento del pensamiento setTimeout con 1 milisecond por clic.

  $("#element").click(function(){
     $(this).removeClass("blink");

     setTimeout(function(){
       $(this).addClass("blink);
    },1 ///it may be only 1 milisecond, it's enough
  });
 5
Author: Viktor Mezhenskyi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-28 15:31:33
  1. Implementar la animación como un descriptor CSS
  2. Añadir el descriptor a un elemento para iniciar la animación
  3. Use una función de controlador de eventos animationend para eliminar el descriptor cuando se complete la animación, de modo que esté listo para ser agregado de nuevo la próxima vez que desee reiniciar la animación.

---HTML---

<div id="animatedText">
Animation happens here
</div>

<script>

  function startanimation(element) {

    element.classList.add("animateDescriptor");

    element.addEventListener( "animationend",  function() {

      element.classList.remove("animateDescriptor");    

    } );

  }

</script>


<button onclick="startanimation( document.getElementById('animatedText') )">
Click to animate above text
</button>

---CSS - - -

@keyframes fadeinout {  
      from { color: #000000; }  
    25% {color: #0000FF; }  
    50% {color: #00FF00; }      
    75% {color: #FF0000; }  
      to { color : #000000; }   
  } 

  .animateDescriptor {  
    animation: fadeinout 1.0s;  
  }     

Pruébalo aquí:

Https://jsfiddle.net/bigjosh/avp9Lk6r/50 /

 1
Author: bigjosh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-19 01:51:23

En esta página puede leer sobre reiniciar la animación del elemento: https://css-tricks.com/restart-css-animation / este es mi ejemplo:

 <head>
        <style>
            @keyframes selectss
{
    0%{opacity: 0.7;transform:scale(1);} 
    100%{transform:scale(2);opacity: 0;}
}
        </style>
        <script>
            function animation()
            {
                var elm = document.getElementById('circle');
                elm.style.animation='selectss 2s ease-out';
                var newone = elm.cloneNode(true);
                elm.parentNode.replaceChild(newone, elm);
            }
        </script>
    </head>
    <body>
        <div id="circle" style="height: 280px;width: 280px;opacity: 0;background-color: aqua;border-radius: 500px;"></div>
        <button onclick="animation()"></button>
    </body>

Pero si lo desea, puede eliminar el elemento de animación y luego devolverlo:

function animation()
        {
            var elm = document.getElementById('circle');
            elm.style.animation='';
            setTimeout(function () {elm.style.animation='selectss 2s ease-out';},10)
        }

Espero haber ayudado!

 0
Author: Ron Cohen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-17 12:20:28

Cree un segundo "fotograma clave@" que reinicie la animación, solo que el problema con esto no puede establecer ninguna propiedad de animación para la animación de reinicio (simplemente vuelve a aparecer)

----- HTML -----

<div class="slide">
    Some text..............
    <div id="slide-anim"></div>
</div><br>
    <button onclick="slider()"> Animation </button>
    <button id="anim-restart"> Restart Animation </button>
<script>
    var animElement = document.getElementById('slide-anim');
    document.getElementById('anim-restart').addEventListener("mouseup", restart_slider);

    function slider() {
        animElement.style.animationName = "slider";             // other animation properties are specified in CSS
    }
    function restart_slider() {
        animElement.style.animation = "slider-restart";         
    }
</script>

----- CSS -----

.slide {
    position: relative;
    border: 3px black inset;
    padding: 3px;
    width: auto;
    overflow: hidden;
}
.slide div:first-child {
    position: absolute;
    width: 100%;
    height: 100%;
    background: url(wood.jpg) repeat-x;
    left: 0%;
    top: 0%;            
    animation-duration: 2s;
    animation-delay: 250ms;
    animation-fill-mode: forwards;
    animation-timing-function: cubic-bezier(.33,.99,1,1); 
}

@keyframes slider {
    to {left: 100%;}
}

@keyframes slider-restart {
    to {left: 0%;}
}
 0
Author: Pall Arpad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-02 07:28:21