JS實(shí)現(xiàn)顏色梯度與漸變效果完整實(shí)例
本文實(shí)例講述了JS實(shí)現(xiàn)顏色梯度與漸變效果的方法。分享給大家供大家參考,具體如下:
運(yùn)行效果圖如下:

完整實(shí)例代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript 顏色梯度和漸變效果</title>
<script type="text/javascript">
var $ = function (id) {
return "string" == typeof id ? document.getElementById(id) : id;
};
var Extend = function(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
var Map = function(array, callback, thisObject){
if(array.map){
return array.map(callback, thisObject);
}else{
var res = [];
for (var i = 0, len = array.length; i < len; i++) { res.push(callback.call(thisObject, array[i], i, array)); }
return res;
}
}
var ColorGrads = function(options){
this.SetOptions(options);
this.StartColor = this.options.StartColor;
this.EndColor = this.options.EndColor;
this.Step = Math.abs(this.options.Step);
};
ColorGrads.prototype = {
//設(shè)置默認(rèn)屬性
SetOptions: function(options) {
this.options = {//默認(rèn)值
StartColor: "#fff",//開(kāi)始顏色
EndColor: "#000",//結(jié)束顏色
Step: 20//漸變級(jí)數(shù)
};
Extend(this.options, options || {});
},
//獲取漸變顏色集合
Create: function() {
var colors = [],
startColor = this.GetColor(this.StartColor),
endColor = this.GetColor(this.EndColor),
stepR = (endColor[0] - startColor[0]) / this.Step,
stepG = (endColor[1] - startColor[1]) / this.Step,
stepB = (endColor[2] - startColor[2]) / this.Step;
//生成顏色集合
for(var i = 0, n = this.Step, r = startColor[0], g = startColor[1], b = startColor[2]; i < n; i++){
colors.push([r, g, b]); r += stepR; g += stepG; b += stepB;
}
colors.push(endColor);
//修正顏色值
return Map(colors, function(x){ return Map(x, function(x){
return Math.min(Math.max(0, Math.floor(x)), 255);
});});
},
//獲取顏色數(shù)據(jù)
GetColor: function(color) {
if(/^#[0-9a-f]{6}$/i.test(color))
{//#rrggbb
return Map([color.substr(1, 2), color.substr(3, 2), color.substr(5, 2)],
function(x){ return parseInt(x, 16); }
)
}
else if(/^#[0-9a-f]{3}$/i.test(color))
{//#rgb
return Map([color.substr(1, 1), color.substr(2, 1), color.substr(3, 1)],
function(x){ return parseInt(x + x, 16); }
)
}
else if(/^rgb(.*)$/i.test(color))
{//rgb(n,n,n) or rgb(n%,n%,n%)
return Map(color.match(/\d+(\.\d+)?\%?/g),
function(x){ return parseInt(x.indexOf("%") > 0 ? parseFloat(x, 10) * 2.55 : x, 10); }
)
}
else
{//color
var mapping = {"red":"#FF0000"};//略
color = mapping[color.toLowerCase()];
if(color){
return Map([color.substr(1, 2), color.substr(3, 2), color.substr(5, 2)],
function(x){ return parseInt(x, 16); }
)
}
}
}
};
var CurrentStyle = function(element){
return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}
var Bind = function(object, fun) {
var args = Array.prototype.slice.call(arguments).slice(2);
return function() {
return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
}
}
//漸變對(duì)象
var ColorTrans = function(obj, options){
this._obj = $(obj);
this._timer = null;//定時(shí)器
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 = {
//設(shè)置默認(rèn)屬性
SetOptions: function(options) {
this.options = {//默認(rèn)值
StartColor: "",//開(kāi)始顏色
EndColor: "#000",//結(jié)束顏色
Step: 20,//漸變級(jí)數(shù)
Speed: 20,//漸變速度
CssColor: "color"http://設(shè)置屬性(Scripting屬性)
};
Extend(this.options, options || {});
},
//重設(shè)顏色集合
Reset: function(color) {
//修改顏色后必須重新獲取顏色集合
color = Extend({ StartColor: this._startColor, EndColor: this._endColor, Step: this._step }, color || {});
//設(shè)置屬性
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);
}
},
//顏色設(shè)置
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);
}
};
</script>
</head>
<body>
<style type="text/css">
#idGrads{}
#idGrads div{ font-size:0;height:1px;}
</style>
<div id="idGrads"> </div>
<script>
var forEach = function(array, callback, thisObject){
if(array.forEach){
array.forEach(callback, thisObject);
}else{
for (var i = 0, len = array.length; i < len; i++) { callback.call(thisObject, array[i], i, array); }
}
}
var colors = new ColorGrads({ StartColor: "#fff", EndColor: "rgb(20,127,0)" }).Create();
forEach(colors.concat().concat(colors.reverse()), function(x){
$("idGrads").innerHTML += "<div style=\"background-color:"+"rgb(" + x[0] + "," + x[1] + "," + x[2] + ");\"></div>";
})
</script>
<Br />
<Br />
<style type="text/css">
#idMenu{ background:#DBDBDB;text-align:center;line-height:25px; table-layout:fixed;}
#idMenu td{ cursor:pointer;}
</style>
<table id="idMenu" width="600" border="0" cellspacing="5" cellpadding="0">
<tr>
<td onclick="location.href='#'">Cropper</td>
<td onclick="location.href='#'">Tween</td>
<td onclick="location.href='#'">Slider</td>
<td onclick="location.href='#'">Resize</td>
<td onclick="location.href='#'">Drag</td>
</tr>
</table>
<script>
forEach($("idMenu").getElementsByTagName("td"), function(x, i){
var ct1 = new ColorTrans(x, { StartColor: "#666", EndColor: "#fff" });
var ct2 = new ColorTrans(x, { StartColor: "#f6f6f6", EndColor: "rgb(20,150,0)", CssColor: "backgroundColor" });
x.onmouseover = function(){ ct1.FadeIn(); ct2.FadeIn(); }
x.onmouseout = function(){ ct1.FadeOut(); ct2.FadeOut(); }
})
</script>
<Br />
<Br />
<div id="idRandom" style="padding:10px;color:#fff; background-color:#CCC;">點(diǎn)擊隨機(jī)換顏色</div>
<script>
var ctRandom = new ColorTrans("idRandom", { EndColor: "#CCC", CssColor: "backgroundColor" })
$("idRandom").onclick = function(){
var rgb = Map([1,1,1], function(){ return Math.floor((Math.random() * 255)); } );
ctRandom.Reset({ StartColor: this.style.backgroundColor, EndColor: "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")" })
ctRandom.FadeIn();
}
</script>
</body>
</html>
PS:這里再為大家推薦幾款本站的相關(guān)在線工具:
在線RGB、HEX顏色代碼生成器:
http://tools.jb51.net/color/rgb_color_generator
RGB顏色查詢對(duì)照表_顏色代碼表_顏色的英文名稱大全:
http://tools.jb51.net/color/jPicker
在線網(wǎng)頁(yè)調(diào)色板工具:
http://tools.jb51.net/color/color_picker
在線顏色選擇器工具/RGB顏色查詢對(duì)照表:
http://tools.jb51.net/color/colorpicker
更多關(guān)于JavaScript相關(guān)內(nèi)容可查看本站專題:《JavaScript切換特效與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》、《JavaScript動(dòng)畫特效與技巧匯總》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章
MUI 解決動(dòng)態(tài)列表頁(yè)圖片懶加載再次加載不成功的bug問(wèn)題
這篇文章主要介紹了MUI 解決動(dòng)態(tài)列表頁(yè)圖片懶加載再次加載不成功的bug問(wèn)題,解決方法很簡(jiǎn)單的,需要的朋友可以參考下2017-04-04
ionic中的$ionicPlatform.ready事件中的通用設(shè)置
$ionicPlatform.ready事件是用于檢測(cè)當(dāng)前的平臺(tái)是否就緒的事件,相當(dāng)于基于document的deviceready事件, 在app中一些通用關(guān)于設(shè)備的設(shè)置必須在這個(gè)事件中處理2017-06-06
深入理解JavaScript 中的匿名函數(shù)((function() {})();)與變量的作用域
匿名函數(shù)沒(méi)有實(shí)際名字的函數(shù),匿名函數(shù)(function() {})();是一個(gè)特殊的閉包寫法。本文蛀牙給大家介紹JavaScript 中的匿名函數(shù)((function() {})();)與變量的作用域,需要的朋友可以參考下2018-08-08
JS實(shí)現(xiàn)滾動(dòng)條觸底加載更多
這篇文章主要介紹了JS滾動(dòng)條觸底加載更多,需要的朋友可以參考下2019-09-09
JavaScript打印網(wǎng)頁(yè)指定區(qū)域的例子
這篇文章主要介紹了JavaScript打印網(wǎng)頁(yè)指定區(qū)域的例子,需要的朋友可以參考下2014-05-05
基于原生JS實(shí)現(xiàn)分頁(yè)效果的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用原生js實(shí)現(xiàn)分頁(yè)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
前端JS,刪除JSON數(shù)據(jù)(JSON數(shù)組)中的指定元素方式
這篇文章主要介紹了前端JS,刪除JSON數(shù)據(jù)(JSON數(shù)組)中的指定元素方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

