Javascript为动画添加延迟

Javascript add delay to animate

本文关键字:延迟 添加 动画 Javascript      更新时间:2023-09-26

我一直试图给我的一个JavaScript动画添加延迟,但我得到的只是一个错误,上面写着"对象不支持属性或方法'delay'"。顺便说一下,我正在IE 8兼容性上测试这个。

下面是我尝试过的提到的代码。

来自

$('a',$(this)).stop().animate({'marginTop':'200'},1000);

$('a',$(this)).stop().delay(1000).animate({'marginTop':'200'},1000);

这是小提琴。

谨致问候,

Vernon

小提琴上有两个主要问题:

1) 动画代码是在jQuery之前设置的。这就是为什么您在控制台中获得TypeError: $ is not defined。在代码之前将jQuery包含在<head>中,并且不带任何包装函数:

<head>
    ....
    <script>
        /* jQuery here */
    </script>
    <script>
        $(function() {
            /* your code here */
        });
    </script>
    ....
</head>

2) 您使用的是一个非常旧的jQuery版本1.3.2,没有延迟功能。这就是为什么您在呼叫.delay()时会得到TypeError: undefined is not a function。要么使用更新版本的jQuery(>=1.4.3),要么自己定义延迟函数:

$(function() {
    // original $.fn.delay copied from jQuery v1.4.3 source:
    jQuery.fn.delay = function( time, type ) {
        time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
        type = type || "fx";
        return this.queue( type, function() {
            var elem = this;
            setTimeout(function() {
                jQuery.dequeue( elem, type );
            }, time );
        });
    };
    /* Your code here now works with .delay() */
});

在此处更新FIDDLE,插入延迟1500。

类似的东西?

$(function(){$('a','body').on('click',function(e){
        e.preventDefault();
        $(this).delay(1000).animate({marginTop:'200px'},1000);
    })
});

查看Fiddle:http://jsfiddle.net/7hxv3kd4/2/

我对代码进行了以下两项更改,

  1. 更换</br> to <br/>
  2. Jquery library添加到Frameworks&JSFiddle的扩展部分

我相信它运行良好,请参阅:http://jsfiddle.net/7hxv3kd4/3/