转换为jQuery插件

时间:2013-11-07 18:08:44

标签: jquery

我需要帮助在jquery插件中转换此代码

$({left: 20}).animate({left: 0}, {
  duration: 1000,
  easing:'linear',
  step: function() {
    $('#pp').text(this.left);
  },
  complete: function() {
    $('#pp').text(this.left);
  }
});

我希望值'20','0','1000'和'#pp'必须传递给这个插件。我该怎么办?

1 个答案:

答案 0 :(得分:0)

链接到创建jQuery插件:

http://learn.jquery.com/plugins/basic-plugin-creation/

怎么样:

;(function ($) {

    $.fn.myPlugin = function (options) {    

        // define defaults
        var defaults = {
            left1: 20,
            left2: 0,
            duration: 1000
        };

        var o = $.extend(defaults, options);    

        this.each(function() {

            var $this = $(this);

            $({left: o.left1}).animate({left: o.left2}, {
                  duration: o.duration,
                  easing:'linear',
                  step: function() {
                    $this.text(this.left);
                  },
                  complete: function() {
                    $this.text(this.left);
                  }
            });

        });

        return this;
     }

 })(jQuery);
 // end 

用法是这样的:

$('#pp').myPlugin({
      left1: 20,
      left2: 0,
      duration: 1000
});