how to reset a jquery animation to start over?

我与影子孤独终老i 提交于 2019-12-07 00:40:51

问题


I have built a nice piece of code, some animation and some click/hover events, quite a small row of them. I intend to use it on multiple html-documents (it is a game, you have to get right answer and proceed with next question), built together in another html with full-page-slider (I don't want to load DOM multiple times, makes no sense): the unsolved question is: how to reset the code without actually reloading it? how to make it to clear everything so far and start over? I am a beginner, building stuff upon others snippets. I guess it must be something so easy and basic that nobody answered it... The stuff to animate back all what is done previously is no good: too much stuff and binding and unbinding.


回答1:


I had an animation that was keeping the position each time the code ran. To fix it I used:

function(){ $('.target').removeAttr('style'); }

so my code was something like:

$('#target').animate({
  opacity: 'toggle',
  top: '+=100',
  }, 1000, function() {
  $('#target').removeAttr('style'); 
});



回答2:


For jQuery you can use .finish(), and before that, to reset you need a few parameters to the .stop() method.

$(element).stop(true, true);

https://api.jquery.com/stop/




回答3:


$(element).stop(), then re-run your animation.




回答4:


There is no easy answer since it all depends on what you've done, what state you need to reset, what UI elements need to be reset and so on. I guess you have to build your own reset method that sets all things to their initial state or... you could take the easy path and just reload the page.




回答5:


Thank you for patient answers. Both are right:

  • in case of one animation the stop method works.

  • in case of multiple chained animations - sorry, there is no easy way. Reload if you want a short but not so elegant solution. To do it properly - learn javascript to build the logical chain of functions. You can't run long with just jQuery.




回答6:


I do it this way: (not sure if it's entirely right, though)

$(element).stop();
$(element).clearQueue();
$(element).delay(20).animate({ ... });



回答7:


Try .finish().
Example (try spamming the button):

$('button').on('click', function(event) {
  $("div").finish();
  $("div").fadeOut(1000);
});


来源:https://stackoverflow.com/questions/5069841/how-to-reset-a-jquery-animation-to-start-over

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!