JavaScript 顏色梯度和漸變效果
很久沒寫blog,太忙了。沒什么時間寫復雜的東西,重新把顏色漸變效果寫一遍。
關于顏色的效果一般就兩個,顏色梯度變化和樣式的顏色漸變,前者在ie中一般用濾鏡實現。
實例效果
預覽效果1:
這是一個顏色梯度變化演示:
預覽效果2:
一個顏色漸變的菜單:
顏色漸變的有趣應用,點擊隨機顏色漸變: 點擊隨機換顏色
程序說明 【ColorGrads顏色梯度】 程序ColorGrads的作用是通過StartColor和EndColor生成顏色梯度集合。 先說說RGB顏色模式,前兩種比較常用應該都明白他們的區別吧,它用的是16進制表示形式,而我們想要10進制的。 ![]()
![]()
后面兩種可能用的就比較少了,一個用10進制的rgb顏色值表示,另一個用百分比來表示。 ![]()
而關鍵詞大家都很熟悉,要轉化卻很麻煩,因為沒有一定規律只能一個一個對應: ![]()
在Create創建顏色集合程序中獲得開始顏色和結束顏色的數據后,再根據Step(多少步)就可以獲得步長了: ![]()
![]()
正確的顏色值是在0到255之間的,而且是不帶小數的,所以最好修正一下: ![]()
有了顏色梯度集合,只需要設個定時器把集合的值依次顯示就是一個漸變效果了。 ![]()
var color = this._colors[Math.min(Math.max(0, this._index), this._colors.length - 1)];
this._obj.style[this.CssColor] = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ")";
由于顏色集合是根據開始顏色、結束顏色和步數生成的,所以如果要修改這些屬性必須重新生成過集合。 ![]()
在顏色漸變菜單中,并沒有使用鏈接標簽a,原因是a的偽類的顏色并不能直接用js來修改(除非改class)。 在測試過程中還發現一個關于數組的問題,在ie和ff運行alert([,,].length)會分別顯示3和2。 測試中還發現chrome(1.0.154.48)的map一個問題,map是js1.6的Array的方法,ff和chrome都支持(具體看這里)。
使用說明 ColorGrads只有3個屬性設置: ColorTrans只要一個參數,要實現漸變的對象,可設置以下屬性: 具體使用請參考實例。
程序代碼 ColorGrads部分: ![]()
ColorTrans部分: ![]() var ColorTrans = function(obj, options){ this._obj = $(obj); this._timer = null;//定時器 this._index = 0;//索引 this._colors = [];//顏色集合 this._grads = new ColorGrads(); this.SetOptions(options); this.Speed = Math.abs(this.options.Speed); this.CssColor = this.options.CssColor; this._startColor = this.options.StartColor || CurrentStyle(this._obj)[this.CssColor]; this._endColor = this.options.EndColor; this._step = Math.abs(this.options.Step); this.Reset(); this.SetColor(); }; ColorTrans.prototype = { //設置默認屬性 SetOptions: function(options) { this.options = {//默認值 StartColor: "",//開始顏色 EndColor: "#000",//結束顏色 Step: 20,//漸變級數 Speed: 20,//漸變速度 CssColor: "color"//設置屬性(Scripting屬性) }; Extend(this.options, options || {}); }, //重設顏色集合 Reset: function(color) { //修改顏色后必須重新獲取顏色集合 color = Extend({ StartColor: this._startColor, EndColor: this._endColor, Step: this._step }, color || {}); //設置屬性 this._grads.StartColor = this._startColor = color.StartColor; this._grads.EndColor = this._endColor = color.EndColor; this._grads.Step = this._step = color.Step; //獲取顏色集合 this._colors = this._grads.Create(); this._index = 0; }, //顏色漸入 FadeIn: function() { this.Stop(); this._index++; this.SetColor(); if(this._index < this._colors.length - 1){ this._timer = setTimeout(Bind(this, this.FadeIn), this.Speed); } }, //顏色漸出 FadeOut: function() { this.Stop(); this._index--; this.SetColor(); if(this._index > 0){ this._timer = setTimeout(Bind(this, this.FadeOut), this.Speed); } }, //顏色設置 SetColor: function() { var color = this._colors[Math.min(Math.max(0, this._index), this._colors.length - 1)]; this._obj.style[this.CssColor] = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ")"; }, //停止 Stop: function() { clearTimeout(this._timer); } };
|