在高度动画后获取回调

Get callback after height animation

本文关键字:获取 回调 动画 高度      更新时间:2023-09-26

这里我试图在高度动画之后运行一些代码

<button id="btn1">Animate height</button>
<div id="box"style="background:#98bf21;height:100px;width:100px;margin:6px;"></div>
$(document).ready(function () {
  $("#btn1").click(function () {
    $("#box").animate({height:"300px"});
  });
  var x = $('#box').height();
  if(x == 300){alert('animation is finished');}
});

我不能把我想在高度动画后运行的代码放在animate方法回调中,因为动画框脚本放在一个文档中,而我想在另一个文档运行的代码。

使用jquery.proise((.done

$(document).ready(function () {
    $("#btn1").click(function () {
        $("#box").animate({
            height: "300px"
        }).promise().done(function () {
            alert('animation is finished');
        });;
    })
});

或者像这样单独:

$(document).ready(function () {
    $("#btn1").click(function () {
        $("#box").animate({
            height: "300px"
        });
        $("#box").promise().done(function () {
            alert('animation is finished');
        });
    })
});

固定Fiddle

事件驱动的JavaScript a la jQuery:

//file 1
$("#box").animate({height:"300px"},function() {
 $(this).trigger('myBoxFinishedAnimatingHeight');
});
//file 2
$('#box').on('myBoxFinishedAnimatingHeight',function() {
 //your code
});

您可以简单地将complete属性用作回调函数:

.animate( properties [, duration ] [, easing ] [, complete ] )

发件人http://api.jquery.com/animate

这是一个演示

$("#adjest").animate({"height":"300px"},1000);
$("#adjest").promise().done(
   function() {
        alert("done");
    }
);

如果你不能在animate((中运行它,我会使用promise和done。参见此处

http://jsfiddle.net/5p8Ww/

您可以为文件命名空间并调用函数。。。

var NameSpace = Namespace || {};
NameSpace.yourFunction() {
    //Do stuff...
}

然后在您的html/other_file 中

.animate( properties , 1000, ease, NameSpace.yourFunction())