简体   繁体   English

.animate() 并返回到原始状态

[英].animate() and going back to original state

I am a bit new to jQuery, and trying to learn it.我对 jQuery 有点陌生,正在尝试学习它。 I am animating an element after its parent is clicked, but I also want the element to go back to its original state after a set time period.我在单击其父元素后为其设置动画,但我也希望元素在设定的时间段后返回其原始状态。 I did try setTimeout but I may be using it wrong, so it didn't work.我确实尝试过setTimeout但我可能用错了,所以它没有用。 Can someone explain how to do this?有人可以解释如何做到这一点吗?

var span = $('span');

$('button').click(function(){


    span.animate({

      left: '200' }, 500, 'linear',  function() {

      });
     });

You could do that like this.你可以这样做。 You save the original value for left and use the delay() method to chain multiple animations with a time delay between them:您保存 left 的原始值并使用delay()方法链接多个动画,它们之间有一个时间延迟:

var span = $('span');
// insert span into your document somehow
// set absolute positioning on it
$('button').click(function(){
    var origLeft = span.css("left");
    span.animate({left: '200' }, 500, 'linear').delay(2000).animate({left: origLeft}, 500, 'linear');
});

Working demonstration here: http://jsfiddle.net/jfriend00/zB5NL/这里的工作演示: http : //jsfiddle.net/jfriend00/zB5NL/

It's not perfectly clear what you mean but you could save the initial value of the CSS property and then animate "back" in the callback.您的意思不是很清楚,但您可以保存 CSS 属性的初始值,然后在回调中为“返回”设置动画。 And you should append the span to the DOM before you can animate it.并且您应该先将 span 附加到 DOM,然后才能对其进行动画处理。 Something like:就像是:

var span = $('span');
$('body').append(span);
$('button').click(function() {
    var left = span.css('left');
    span.animate({
        left: '200'
    }, 500, 'linear', function() {
        //animate back to starting position
        span.animate({
        left: left
    }, 500, 'linear');
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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