2016-08-03 36 views
0

Ich habe einige Animationen in einer Funktion. Ich trigger nur die Funktion, wenn das Fenster über 640px ist. Wenn das Fenster über 640px ist, aber die Größe unter 640px geändert wird, möchte ich die laufende Animation vollständig stoppen und meine CSS-Medienabfragen die Elemente stylen lassen. Ich habe mir die Stop-Methode, Clearqueue und Methoden angeschaut, kann sie aber nicht richtig für das verwenden, was ich versuche.jQuery Javascript: Wie kann ich verhindern, dass die laufende Animation ausgeführt wird, wenn die Größe des Fensters geändert wird?

function myAnimations() { 
    // some animations 
} 

$(document).ready(function() { 

    if (!isMobile && winWidth > 640) { 

     myAnimations(); 

     $(window).resize(function() { 
      // checking if window got resized below 640px 

      if (winWidth < 640) { 

       // How do I totally cancel the ongoing animation 
       // which was just triggered before the window got resized ? 
       // So that my css media query can style the elements. 

      } 
     }) 

    } 
    } 

Antwort

0

Dies sollte funktionieren.

if (winWidth < 640) { 
    $("*").is(":animated").stop(); 
} 
0

Wenn Sie nur die jQuery Animationen verwenden, können Sie die .stop() zusammen mit :animated Selektor verwenden.

Wenn Sie stattdessen CSS-Animation verwenden, können Sie sich auf animationend, animationstart, animationiteration events beziehen.

Das Snippet mit einer unendlichen jQuery Animation:

function myAnimations() { 
 
    $('.block').animate({'margin-left':'100px'},2000).animate({'margin-left':'0px'},2000, myAnimations); 
 
} 
 

 

 
$(function() { 
 
    myAnimations(); 
 

 
    
 
    $('#Stop').on('click', function(e) { 
 
    while ($(':animated').length > 0) { 
 
     $(':animated').stop(); 
 
    } 
 
    }) 
 
    
 
    
 
    $('#Start').on('click', function(e) { 
 
    myAnimations(); 
 
    }) 
 
});
div { 
 
    position: absolute; 
 
    background-color: #abc; 
 
    left: 0px; 
 
    top: 30px; 
 
    width: 60px; 
 
    height: 60px; 
 
    margin: 5px; 
 
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> 
 

 
<button id="Stop">Stop animation</button> 
 
<button id="Start">ReStart animation</button> 
 
<div class="block"></div>