Jquery:如何延迟或等待?

60

我想将这个对象向上移动,延迟1000毫秒后再隐藏它。

我得到了以下代码:

$("#test").animate({"top":"-=80px"},1500)
      .animate({"top":"-=0px"},1000)
      .animate({"opacity":"0"},500);

我使用".animate({"top":"-=0px"},1000)"来实现延迟效果,但这不是一个好的方法。

我想要:

$("#test").animate({"top":"-=80px"},1500)
      .sleep(1000)
      .animate({"opacity":"0"},500);
任何想法?
2个回答

95

那么使用.delay()呢?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

4
这在这种情况下可行,但是让线程休眠和延迟效果是两件完全不同的事情。jQuery 在他们的文档中甚至提醒了这一点。 - ars265

56
如果你无法像Robert Harvey建议的那样使用delay方法,你可以使用setTimeout
例如:
setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接