【问题标题】:Delay until jQuery animate has finished延迟到 jQuery 动画完成
【发布时间】:2012-08-01 19:51:26
【问题描述】:

我制作了一个 jQuery 插件,它可以制作启动画面。它使用 jQuery 的 animate 函数,并通过以下方式初始化和触发:

    $('#temperature_splash').splashScreen();

    $('.tempGraphButton').click(function () {

        $('#temperature_splash').splashScreen('splash', 300);

         //Here, I would like to make an ajax request when the animation has finished
    }

我想在插件中的动画完成后发出一个 ajax 请求,但我不知道怎么做。有人有什么建议吗?

插件代码概要

$.fn.splashScreen = function (method) {
    // Method calling logic
    if (methods[method]) {
        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        return methods.init.apply(this, arguments);
    } else {
        $.error('Method ' + method + ' does not exist');
    }
}

var methods = {
    init: function () {
        //Some initializations
    },

    splash: function (time) {
        //Setting some properties

        splashScreenContent.animate({
            width: width,
            left: leftPos
        }, time).animate({
            height: height,
            top: topPos
        }, time);

        return false;
    }
}

})(jQuery);

【问题讨论】:

    标签: jquery jquery-plugins jquery-animate


    【解决方案1】:

    只需添加一个回调

    var methods = {
        init: function () {
            methods.splash(1000, function() {
                //do something when animation is finished
                methods.ajax();
            });
        },
        splash: function (time, callback) {
            splashScreenContent.animate({
                width: width,
                left: leftPos
            }, time).animate({
                height: height,
                top: topPos
            }, time, function() {
                if (typeof callback==='function') callback.call();
            });
    
            return false;
        },
        ajax: function() {
            //do ajax stuff
        }
    }
    

    这只是一个示例,您必须自己弄清楚要传递哪些选项以及如何将其绑定到您的插件中。

    【讨论】:

      【解决方案2】:

      你不能也绑定到 jQuery 中的 .done 特性吗?

      methods.done(function(){ do your code here for the ajax })'

      【讨论】:

      • 自制插件不一定可以访问 Promise,除非您将其添加到插件中。
      【解决方案3】:

      由于这些调用是异步的,您可以将 ajax 代码放在关闭启动代码之前,因为启动函数之后的代码将在启动函数内部的代码之前执行

      【讨论】:

        猜你喜欢
        • 2011-07-10
        • 1970-01-01
        • 2012-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-17
        • 2021-04-14
        • 1970-01-01
        相关资源
        最近更新 更多