简体   繁体   中英

How to Start the animate effects from the initial stage

I'm making a little animate effect, see my fiddle: https://jsfiddle.net/sbhdqhn9/

If I click the finish button the animate ends, but when I start the animate again it does not start from the initial stage where it was started at the very first time. Rather it starts from the point it ended.

 $(function() { $('#go').on('click', function() { $('.box').animate({ 'top': '+=200' }, 2000).animate({ 'left': '+=500' }, 2000).animate({ 'top': '-=200' }, 2000); }); $('#bf').on('click', function() { $('.box').finish(); }); })(); 
 .box { position: absolute; top: 10px; left: 10px; width: 15px; height: 15px; background: black; } #path { height: 244px; font-size: 70%; border-left: 2px dashed red; border-bottom: 2px dashed green; border-right: 2px dashed blue; } button { width: 12em; display: block; text-align: left; margin: 0 auto; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="box"></div> <div id="path"> <button id="go">Go</button> <br/> <button id="bf" class="b">.finish()</button> </div> 

Reset the top and left attributes at the top of your Go button click

...
    $('.box').css('top', '10px');
    $('.box').css('left', '10px');
    $('.box').animate({
        ...

Fiddle - https://jsfiddle.net/vw6o2npy/

You need to save the state of your box before you animate.

var box = $('.box');
var position = null; 
      if(position === null)
      {
          position = box.position();    
      }
      box.css({
          top: position.top + 'px',
          left: position.left + 'px'                    
      });

https://jsfiddle.net/sbhdqhn9/1/

您需要在单击转到按钮或完成按钮时将topleft位置重置为初始状态: $('.box').css({top: '10px', left: '10px'});

What your current code is doing is animating it from whatever location it's at. You should think about how to reset the location when it's clicked for every click, as opposed to how it is now, which simply animates it from whatever location it's already at.

The code given by potatopeelings will work, but you should try doing it yourself so you understand why you're getting undesired results. =)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM