jQuery事件顺序并等待动画完成

时间:2010-03-09 08:38:33

标签: javascript jquery jquery-selectors

我有一个滑块动画,但是在clX.click事件中,#close div会在动画放置-250px之前隐藏。如何等到动画完成然后隐藏#close div?

    $(document).ready(function() {
        $("#open").click(function() {
            if ($("#close").is(":hidden")) {
                $("#open").animate({
                    marginLeft: "-32px"
                }, 200);

                $("#close").show();
                $("#close").animate({
                    marginLeft: "250px"
                }, 500);
            }
        });
        $("#clX").click(function() {
            $("#close").animate({
                marginLeft: "-250px"
            }, 500);

            $("#open").animate({
                marginLeft: "0px"
            }, 200);

            $("#close").hide();
        });
    });

2 个答案:

答案 0 :(得分:11)

您可以为动画添加回调函数。动画结束后会被触发。

$('#clX').click(function() {
  $('#close').animate({
    marginLeft: "-250px"
  }, 500, function() {
    // Animation complete.
    $("#close").hide();
    //i supose $this.hide() <br/>would work also and it is more efficient.
  });
});

答案 1 :(得分:4)

@hasan,methinks @patxi意味着$(this)

var closeable = $('#close');
$('#clx').bind('click', function(){
   // $(this) === $('#clx')
   closeable.stop().animate({marginLeft:'-250px'},{
     duration: 500,
     complete: function(){
        $(this).hide(); 
        // $(this) === closeable;
     }
   });
});