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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2407592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:11:13  来源:igfitidea点击:

jQuery event order and waiting till animation complete

javascriptjqueryjquery-selectors

提问by HasanG

I have an slider animation but on clX.click event #close div hides before it is animated -250px left. How to wait till the animation completes and then hide #close div?

我有一个滑块动画,但在 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();
        });
    });

回答by Patxi1980

You can add a callback function to the animation. It would be fired once the animation is finished.

您可以向动画添加回调函数。一旦动画完成,它就会被触发。

$('#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.
  });
});

回答by Quickredfox

@hasan, methinks @patxi meant $(this)

@hasan,我认为@patxi 的意思是 $(this)

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