0

我需要创建一个返回 jQuery.Color 对象的函数,但我不知道该怎么做。这是代码示例

function newcolor () { var obj =  new $.Color( 'rgb(0,0,0)' ); return obj;}

var foo = newcolor();

foo.red();

编辑:

我的完整代码:

function my (element,a,b,c){ //class my
   this.target = $(elem);
   this.new_color = function (a,b,c) { return new $.Color( 'rgb('+a+','+b+','+c+')'); }
   this.base_color = new_color (a,b,c);
   this.colorize = function () ( this.target.css({ background-color: new_color });
}

var div = new My($('foo'),0,0,0);
div.new_color(255,255,255);
div.colorize();

我的目标是创建可以容纳 jquery 元素并对其进行操作的类。现在我坚持返回 $.Color()。

4

1 回答 1

1

像这样的东西怎么样:

function My(elem,r,g,b){ //class my

  this.setColor = function(r,g,b) {
    this.r = (r || 0);
    this.g = (g || 0);
    this.b = (b || 0);
  };

  this.colorArray = function() {
    return [this.r, this.g, this.b];
  };

  this.colorString = function() {
    return "rgb(" + this.colorArray().join(",") + ")";
  };

  this.colorize = function(r,g,b) {
    if (r && g && b) {
      this.setColor(r,g,b);
    }
    var color = $.Color(this.colorString());
    this.target.css({backgroundColor: color});
  }

  // initialize
  this.target = $(elem);
  this.setColor(r,g,b);
  this.colorize();
};

var div1 = new My($('#div1'),100,20,40);
div1.setColor(255,255,200);
div1.colorize();

var div2 = new My($('#div2'),100,20,40);

您会注意到,我基本上添加了一些包装函数,并且只是为实例存储了单独的 r、g、b 值。然后您只在需要时才在最后一分钟调用 j1Query.Color 方法。那么就没有必要在周围放置颜色实例了。

我也把它放在了codepen上: http ://codepen.io/bunnymatic/pen/yLxwp

于 2013-11-09T20:43:52.017 回答