1

I'm having trouble figuring out callbacks, or whatever this is. I'm using some jquery addon called easing and what is supposed to happen is you click a button, and a div flies in from the left, then when you click on the x on that div, it flies out the right. Problem is, when you click it again it flies in from the right and out the right. What I want to do is have the div appear back at its original position when the animation finishes playing.

<script>
$(document).ready(function() {
    $('#button').click(function(event) {
        $('#animdiv')
            .animate(
                { left: 170 }, {
                    duration: 'slow',
                    easing: 'easeOutBack'
                });
});
    $('#exit').click(function(event) {
        $('#animdiv')
            .animate(
                { left: 1200 }, {
                    duration: 'slow',
                    easing: 'easeOutBack'
                });
    });
});
// this is the function that takes it back to it's original place
function placeDiv(x_pos, y_pos) {
  var d = document.getElementById('animdiv');
  d.style.position = "absolute";
  d.style.left = -600;
  d.style.top = 32;
}

</script>
4

2 回答 2

4

.animate接受一个回调函数,该函数仅在动画完成后运行:

$('#exit').click(function(event) {
    $('#animdiv')
        .animate(
            { left: 1200 }, {
                duration: 'slow',
                easing: 'easeOutBack',
                complete: placeDiv
            });
});

但是,在您添加样式placeDiv之前,您的功能将无法工作:px

function placeDiv() {
  var d = document.getElementById('animdiv');
  d.style.position = "absolute";
  d.style.left = "-600px";
  d.style.top = "32px";
}

或者使用 jQuery(它将px为您添加):

function placeDiv() {
  $('#animdiv').css({
    position: "absolute",
    left: -600,
    top: 32
  });
}

http://jsfiddle.net/mblase75/M6xGC/


或者,如果您想传递 x 和 y 值:

$('#exit').click(function (event) {
    var xpos = -600,
        ypos = 32;
    $('#animdiv')
        .animate({
        left: 1200
    }, {
        duration: 'slow',
        easing: 'easeOutBack',
        complete: function() { placeDiv(xpos,ypos); }
    });
});

和回调:

function placeDiv(x,y) {
  $('#animdiv').css({
    position: "absolute",
    left: x,
    top: y
  });
}

http://jsfiddle.net/mblase75/M6xGC/4/

于 2013-05-28T15:20:31.017 回答
0

哈哈,不知道动画完成后有回调。用那个。忘记我的回答。

这样做的几种方法 -

  1. 飞出的 div 可以从右到左发生。在这种情况下,您需要做的就是更改退出单击的左值 -

    $('#exit').click(function(event) {
        $('#animdiv')
            .animate(
                { left: -600 }, {
                    duration: 'slow',
                    easing: 'easeOutBack'
                });
    });
    
  2. 在为条目设置动画之前,隐藏 div,重新定位到 -600px,更改为 display: block 再次动画 -

    $('#button').click(function(event) {
        $('#animdiv').hide().css('left', '-600px').show()
            .animate(
                { left: 170 }, {
                    duration: 'slow',
                    easing: 'easeOutBack'
                });
    
于 2013-05-28T15:21:47.913 回答