2013-11-09 59 views
0

我需要創建一個函數,它將返回jQuery.Color對象,我不知道該怎麼做。下面是代碼示例如何從自己的函數運行Jquery構造函數?

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()。

回答

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

+0

你甚至可以把它進一步使'setColor'運行'colorize'所以你打電話的setColor即每次,顏色更新。 –

+0

感謝您的幫助和時間,我會嘗試將其實現到我的代碼並查看它是如何工作的。 – Invidian

相關問題