JS教程:制作颜色梯度和渐变效果

  • 序二(09/11/1)
    近来看了Dean的“Convert any colour value to hex in MSIE”,终于解决了根据关键字获取颜色rgb值的问题。
    顺便把程序也重新整理一番,并使用了最近整理的工具库。
  • 序一(09/03/11)
    很久没写blog,太忙了。没什么时间写复杂的东西,重新把颜色渐变效果写一遍。
    关于颜色的效果一般就两个,颜色梯度变化和颜色动态渐变,前者在ie中一般用滤镜实现。

效果预览

运行代码框
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>JavaScript 颜色梯度和渐变效果</title>
<script type="text/javascript">
eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]e}];e=function(){return'([3-59cf-hj-mo-rt-yCG-NP-RT-Z][12]\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('5 $$,$$B,$$A,$$F,$$D,$$E,$$S;(3(){5 O,B,A,F,D,E,S;O=3(id){4"1L"==1t id?P.getElementById(id):id};O.extend=3(G,10){H(5 Q R 10){G[Q]=10[Q]}4 G};O.deepextend=3(G,10){H(5 Q R 10){5 17=10[Q];9(G===17)continue;9(1t 17==="c"){G[Q]=I.callee(G[Q]{},17)}J{G[Q]=17}}4 G};B=(3(K){5 b={11:/11/.x(K)&&!/1u/.x(K),1u:/1u/.x(K),1M:/webkit/.x(K)&&!/1v/.x(K),1N:/1N/.x(K),1v:/1v/.x(K)};5 1i="";H(5 i R b){9(b[i]){1i="1M"==i?"18":i;19}}b.18=1i&&1w("(?:"+1i+")[\\\\/: ]([\\\\d.]+)").x(K)?1w.$1:"0";b.ie=b.11;b.1O=b.11&&1y(b.18)==6;b.ie7=b.11&&1y(b.18)==7;b.1P=b.11&&1y(b.18)==8;4 b})(1z.navigator.userAgent.toLowerCase());A=3(){5 l={isArray:3(1Q){4 Object.1R.toString.L(1Q)==="[c 1S]"},1A:3(C,12,p){9(C.1A){4 C.1A(12)}J{5 M=C.1a;p=1T(p)?0:(p<0)?1j.1U(p)+M:1j.1V(p);H(;p<M;p++){9(C[i]===12)4 i}4-1}},1B:3(C,12,p){9(C.1B){4 C.1B(12)}J{5 M=C.1a;p=1T(p)p>=M-1?M-1:p<0?1j.1U(p)+M:1j.1V(p);H(;p>-1;p--){9(C[i]===12)4 i}4-1}}};3 X(c,q){9(undefined===c.1a){H(5 f R c){9(w===q(c[f],f,c))19}}J{H(5 i=0,M=c.1a;i<M;i++){9(i R c){9(w===q(c[i],i,c))19}}}};X({1W:3(c,q,j){X.L(j,c,3(){q.Y(j,I)})},map:3(c,q,j){5 l=[];X.L(j,c,3(){l.1X(q.Y(j,I))});4 l},1k:3(c,q,j){5 l=[];X.L(j,c,3(1Y){q.Y(j,I)&&l.1X(1Y)});4 l},every:3(c,q,j){5 l=1b;X.L(j,c,3(){9(!q.Y(j,I)){l=w;4 w}});4 l},some:3(c,q,j){5 l=w;X.L(j,c,3(){9(q.Y(j,I)){l=1b;4 w}});4 l}},3(1Z,f){l[f]=3(c,q,j){9(c[f]){4 c[f](q,j)}J{4 1Z(c,q,j)}}});4 l}();F=(3(){5 1c=1S.1R.1c;4{bind:3(1l,j){5 1m=1c.L(I,2);4 3(){4 1l.Y(j,1m.20(1c.L(I)))}},bindAsEventListener:3(1l,j){5 1m=1c.L(I,2);4 3(g){4 1l.Y(j,[E.1d(g)].20(1m))}}}})();D={1n:3(m){5 13=m?m.21:P;4 13.22.2313.24.23},1o:3(m){5 13=m?m.21:P;4 13.22.2513.24.25},1C:3(a,b){4(u.1C=a.26?3(a,b){4!!(a.26(b)&16)}:3(a,b){4 a!=b&&a.1C(b)})(a,b)},v:3(m){5 o=0,N=0,T=0,U=0;9(!m.27B.1P){5 n=m;while(n){o+=n.offsetLeft,N+=n.offsetTop;n=n.offsetParent};T=o+m.offsetWidth;U=N+m.offsetHeight}J{5 v=m.27();o=T=u.1o(m);N=U=u.1n(m);o+=v.o;T+=v.T;N+=v.N;U+=v.U};4{"o":o,"N":N,"T":T,"U":U}},clientRect:3(m){5 v=u.v(m),1D=u.1o(m),1E=u.1n(m);v.o-=1D;v.T-=1D;v.N-=1E;v.U-=1E;4 v},28:3(k){4(u.28=P.1p?3(k){4 P.1p.29(k,2a)}:3(k){4 k.1q})(k)},2b:3(k,f){4(u.2b=P.1p?3(k,f){5 h=P.1p.29(k,2a);4 f R h?h[f]:h.getPropertyValue(f)}:3(k,f){5 h=k.1q;9(f=="Z"){9(/1F\\(Z=(.*)\\)/i.x(h.1k)){5 Z=parseFloat(1w.$1);4 Z?Z/2c:0}4 1};9(f=="2d"){f="2e"}5 l=h[f]h[S.1G(f)];9(!/^\\-?\\d+(px)?$/i.x(l)&&/^\\-?\\d/.x(l)){h=k.h,o=h.o,2g=k.1H.o;k.1H.o=k.1q.o;h.o=l0;l=h.pixelLeft+"px";h.o=o;k.1H.o=2g}4 l})(k,f)},setStyle:3(1e,h,14){9(!1e.1a){1e=[1e]}9(1t h=="1L"){5 s=h;h={};h[s]=14}A.1W(1e,3(k){H(5 f R h){5 14=h[f];9(f=="Z"&&B.ie){k.h.1k=(k.1q.1k"").2h(/1F\\([^)]*\\)/,"")+"1F(Z="+14*2c+")"}J 9(f=="2d"){k.h[B.ie?"2e":"cssFloat"]=14}J{k.h[S.1G(f)]=14}}})}};E=(3(){5 1f,1g,15=1;9(1z.2i){1f=3(r,t,y){r.2i(t,y,w)};1g=3(r,t,y){r.removeEventListener(t,y,w)}}J{1f=3(r,t,y){9(!y.$$15)y.$$15=15++;9(!r.V)r.V={};5 W=r.V[t];9(!W){W=r.V[t]={};9(r["on"+t]){W[0]=r["on"+t]}}W[y.$$15]=y;r["on"+t]=1r};1g=3(r,t,y){9(r.V&&r.V[t]){delete r.V[t][y.$$15]}};3 1r(){5 1s=1b,g=1d();5 W=u.V[g.t];H(5 i R W){u.$$1r=W[i];9(u.$$1r(g)===w){1s=w}}4 1s}}3 1d(g){9(g)4 g;g=1z.g;g.pageX=g.clientX+D.1o();g.pageY=g.clientY+D.1n();g.target=g.srcElement;g.1J=1J;g.1K=1K;switch(g.t){2j"mouseout":g.2k=g.toElement;19;2j"mouseover":g.2k=g.fromElement;19};4 g};3 1J(){u.cancelBubble=1b};3 1K(){u.1s=w};4{"1f":1f,"1g":1g,"1d":1d}})();S={1G:3(s){4 s.2h(/-([a-z])/ig,3(all,2l){4 2l.toUpperCase()})}};9(B.1O){try{P.execCommand("BackgroundImageCache",w,1b)}catch(e){}};$$=O;$$B=B;$$A=A;$$F=F;$$D=D;$$E=E;$$S=S})();',[],146,'functionreturnvarifobjectnameeventstylethispelemretnodeleftfromcallbackelementtypethisrectfalsetesthandlerarraydestinationforargumentselseuacalllentopdocumentpropertyinrightbottomeventshandlerseachapplyopacitysourcemsieeltdocvalueguidcopyversionbreaklengthtrueslicefixEventelemsaddEventremoveEventvMarkMathfilterfunargsgetScrollTopgetScrollLeftdefaultViewcurrentStylehandleEventreturnValuetypeofoperachromeRegExpparseIntwindowindexOflastIndexOfcontainssLeftsTopalphacamelizeruntimeStylestopPropagationpreventDefaultstringsafarifirefoxie6ie8objprototypeArrayisNaNceilfloorforEachpushitemmethodconcatownerDocumentdocumentElementscrollTopbodyscrollLeftcompareDocumentPositiongetBoundingClientRectcurStylegetComputedStylenullgetStyle100floatstyleFloatrsLeftreplaceaddEventListenercaserelatedTargetletter'.split(''),0,{}))
</script>
<script type="text/javascript">
//获取颜色梯度方法
var ColorGrads = (function(){
//获取颜色梯度数据
function GetStep(start, end, step) {
var colors = [], start = GetColor(start), end = GetColor(end),
stepR = (end[0] - start[0]) / step,
stepG = (end[1] - start[1]) / step,
stepB = (end[2] - start[2]) / step;
//生成颜色集合
for(var i = 0, r = start[0], g = start[1], b = start[2]; i < step; i++){
colors[i] = [r, g, b]; r += stepR; g += stepG; b += stepB;
}
colors[i] = end;
//修正颜色值
return $$A.map(colors, function(x){ return $$A.map(x, function(x){
return Math.min(Math.max(0, Math.floor(x)), 255);
});});
}
//获取颜色数据
var frag;
function GetColor(color) {
var ret = GetData(color);
if (ret === undefined) {
if (!frag) {
frag = document.createElement("textarea");
frag.style.display = "none";
document.body.insertBefore(frag, document.body.childNodes[0]);
};
try { frag.style.color = color; } catch(e) { return [0, 0, 0]; }//ie opera
if (document.defaultView) {
//opera #rrggbb
ret = GetData(document.defaultView.getComputedStyle(frag, null).color);
} else {
color = frag.createTextRange().queryCommandValue("ForeColor");
ret = [ color & 0x0000ff, (color & 0x00ff00) >>> 8, (color & 0xff0000) >>> 16 ];
}
}
return ret;
}
//获取颜色数组
function GetData(color) {
var re = RegExp;
if (/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.test(color)) {
//#rrggbb
return $$A.map([ re.$1, re.$2, re.$3 ], function(x){
return parseInt(x, 16);
});
} else if (/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test(color)) {
//#rgb
return $$A.map([ re.$1, re.$2, re.$3 ], function(x){
return parseInt(x + x, 16);
});
} else if (/^rgb\((.*),(.*),(.*)\)$/i.test(color)) {
//rgb(n,n,n) or rgb(n%,n%,n%)
return $$A.map([ re.$1, re.$2, re.$3 ], function(x){
return x.indexOf("%") > 0 ? parseFloat(x, 10) * 2.55 : x 0;
});
}
}
return function(colors, step){
var ret = [], len = colors.length;
if ( step === undefined ) { step = 20; }
if ( len == 1 ) {
ret = GetStep( colors[0], colors[0], step );
} else if ( len > 1 ) {
for(var i = 0, n = len - 1; i < n; i++){
var steps = GetStep( colors[i], colors[i+1], step );
i < n - 1 && steps.pop();
ret = ret.concat(steps);
}
}
return ret;
}
})();
//渐变对象
var ColorTrans = function(elem, options){
this._elem = $$(elem);
this._timer = null;//定时器
this._index = 0;//索引
this._colors = [];//颜色集合
this._options = {};//参数对象
this._setOptions(options);
this.speed = Math.abs(this.options.speed);
this.style = this.options.style;
this.reset({
from: this.options.from $$D.getStyle(this._elem, this.style),
to: this.options.to,
step: Math.abs(this.options.step)
});
this._set();
};
ColorTrans.prototype = {
//设置默认属性
_setOptions: function(options) {
this.options = {//默认值
from: "",//开始颜色(默认空值方便自动获取)
to: "#000",//结束颜色
step: 20,//渐变级数
speed: 20,//渐变速度
style: "color"//设置属性(Scripting属性)
};
$$.extend(this.options, options {});
},
//重设颜色集合
reset: function(options) {
//根据参数设置属性
this._options = options = $$.extend( this._options, options {} );
//获取颜色集合
this._colors = ColorGrads( [ options.from, options.to ], options.step );
this._index = 0;
},
//颜色渐入
transIn: function() {
this.stop(); this._index++; this._set();
if(this._index < this._colors.length - 1){
this._timer = setTimeout($$F.bind( this.transIn, this ), this.speed);
}
},
//颜色渐出
transOut: function() {
this.stop(); this._index--; this._set();
if(this._index > 0){
this._timer = setTimeout($$F.bind( this.transOut, this ), this.speed);
}
},
//颜色设置
_set: function() {
var color = this._colors[Math.min(Math.max(0, this._index), this._colors.length - 1)];
this._elem.style[this.style] = "rgb(" + color.join(",") + ")";
},
//停止
stop: function() {
clearTimeout(this._timer);
}
};
</script>
</head>
<body>
<style type="text/css">
#idGrads div{height:1px;overflow:hidden;}
</style>
颜色梯度变化演示:
<div id="idGrads"> </div>
<Br />
<input id="idGradsColor" type="text" value="green"/>
<input id="idGradsSet" type="button" value="设置颜色">
<script>
($$("idGradsSet").onclick = function(){
var colors = ColorGrads( ["#fff", $$("idGradsColor").value], 50 );
$$("idGrads").innerHTML = $$A.map(colors.concat().concat(colors.reverse()), function(x){
return "<div style='background:rgb(" + x.join(",") + ")'></div>";
}).join("");
})()
</script>
<Br />
<Br />
<style type="text/css">
#idPicker ul{float:left;}
#idPicker li{overflow:hidden;width:10px;height:10px;line-height:0;font-size:0;}
#idPicker li.on{width:8px;height:8px; border:1px solid #000;}
#idPicker ul, #idPicker li{list-style:none;margin:0;padding:0;}
#idPicker:after{content:".";display:block;visibility:hidden;height:0;clear:both;}
#idPicker{zoom:1;}
</style>
简单的颜色拾取器: <Br />
选择颜色: <span id="idPickerShow"> </span>
<div id="idPicker"> </div>
<script>
$$("idPicker").innerHTML = "<ul>" +
$$A.map(ColorGrads( ["red", "yellow", "blue"], 10 ), function(x){
return $$A.map(ColorGrads( ["#fff", "rgb(" + x.join(",") + ")" ,"#000"], 10 ),
function(x){
return "<li style='background:rgb(" + x.join(",") + ")'></li>";
}
).join("");
}).join("</ul><ul>") + "</ul>";
var oPickerShow = $$("idPickerShow");
$$A.forEach($$("idPicker").getElementsByTagName("li"), function(li){
li.onmouseover = function(){
this.className = "on";
oPickerShow.innerHTML = oPickerShow.style.backgroundColor
= this.style.backgroundColor;
}
li.onmouseout = function(){ this.className = ""; }
})
</script>
<Br />
<Br />
<style type="text/css">
#idMenu{ background:#DBDBDB;text-align:center;line-height:25px; table-layout:fixed;}
#idMenu td{ cursor:pointer; color:#666; background:#f6f6f6;}
</style>
颜色渐变菜单:
<table id="idMenu" width="600" border="0" cellspacing="5" cellpadding="0">
<tr>
<td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/07/21/ImgCropper.html">Cropper</a></td>
<td><a href="http://www.cnblogs.com/cloudgamer/archive/2009/01/06/Tween.html">Tween</a></td>
<td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/12/24/Slider.html">Slider</a></td>
<td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/12/03/Resize.html">Resize</a></td>
<td><a href="http://www.cnblogs.com/cloudgamer/archive/2008/11/17/Drag.html">Drag</a></td>
<td><a href="http://www.cnblogs.com/cloudgamer/archive/2009/07/07/FixedTips.html">Tooltips</a></td>
</tr>
</table>
<script>
$$A.forEach($$("idMenu").getElementsByTagName("td"), function(x, i){
var a = x.getElementsByTagName("a")[0], href = a.href, txt = a.innerHTML;
x.onclick = function(){ location.href = href; }
x.innerHTML = txt;
var ct1 = new ColorTrans(x, { to: "white" });
var ct2 = new ColorTrans(x, { to: "rgb(20,150,0)", style: "backgroundColor" });
x.onmouseover = function(){ ct1.transIn(); ct2.transIn(); }
x.onmouseout = function(){ ct1.transOut(); ct2.transOut(); }
})
</script>
<Br />
<Br />
<style type="text/css">
#idRandom{padding:10px; background:#CCC; color:#fff;}
</style>
点击随机颜色渐变:
<div id="idRandom"><b>点击随机换颜色</b></div>
<script>
var ctRandom = new ColorTrans("idRandom", { style: "backgroundColor" }),
ctRandom2 = new ColorTrans("idRandom");
$$("idRandom").onclick = function(){
var rgb = $$A.map([1,1,1], function(){ return Math.floor((Math.random() * 255)); } ),
rgb2 = $$A.map(rgb, function(x){ return 255 - x; } );
ctRandom.reset({ from: this.style.backgroundColor, to: "rgb(" + rgb.join(",") + ")" })
ctRandom.transIn();
ctRandom2.reset({ from: this.style.color, to: "rgb(" + rgb2.join(",") + ")" })
ctRandom2.transIn();
}
</script>
</body>
</html>
[Ctrl+A 全部选择 提示:你可先修改部分代码,再按运行]

时间: 2024-12-31 22:48:28

JS教程:制作颜色梯度和渐变效果的相关文章

JavaScript 颜色梯度和渐变效果

序二(09/11/1) 近来看了Dean的"Convert any colour value to hex in MSIE",终于解决了根据关键字获取颜色rgb值的问题. 顺便把程序也重新整理一番,并使用了最近整理的工具库. 序一(09/03/11) 很久没写blog,太忙了.没什么时间写复杂的东西,重新把颜色渐变效果写一遍. 关于颜色的效果一般就两个,颜色梯度变化和颜色动态渐变,前者在ie中一般用滤镜实现. 效果预览 颜色梯度变化演示: 简单的颜色拾取器(点击修改梯度演示颜色): 

JavaScript 颜色梯度和渐变效果第1/3页_javascript技巧

程序说明 [ColorGrads颜色梯度] 程序ColorGrads的作用是通过StartColor和EndColor生成颜色梯度集合. 颜色都可以用红(r).绿(g).蓝(b)三个颜色来表示. 程序中先通过GetColor把一般的颜色表示形式转化成一个用红(r).绿(g).蓝(b)三个颜色值作元素的集合. 那就首先要知道有什么颜色表示形式,从w3c的Colors部分可以知道有以下形式: 关键词模式: em { color: red } RGB颜色模式: em { color: #f00 } e

JS实现的颜色实时渐变效果完整实例_javascript技巧

本文实例讲述了JS实现的颜色实时渐变效果.分享给大家供大家参考,具体如下: <!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

Illustrator制作颜色多彩的漂亮折纸文字效果教程

给各位Illustrator软件的使用者们来详细的解析分享一下制作颜色多彩的漂亮折纸文字效果的教程. 教程分享: 打开Adobe Illustrator软件,执行菜单"文件"/"新建",弹出新建文档对话框,设置名称为:折叠字体效果,设置宽度为:190.5cm,高度为:25.4cm,如图1所示   图1 2.在工具箱中分别选择直接选择工具和矩形工具,在工作区中拖出一个矩形形状,接着鼠标点击矩形,调整成无规则图形,在工具箱中选择设置渐变工具,弹出渐变编辑器,在渐变编辑器

Illustrator制作颜色多彩的漂亮折纸文字效果教程分享

给各位Illustrator软件的使用者们来详细的解析分享一下制作颜色多彩的漂亮折纸文字效果的教程. 教程分享: 效果图:   图01 具体的制作步骤如下: 打开Adobe Illustrator软件,执行菜单"文件"/"新建",弹出新建文档对话框,设置名称为:折叠字体效果,设置宽度为:190.5cm,高度为:25.4cm,如图1所示   图1 2.在工具箱中分别选择直接选择工具和矩形工具,在工作区中拖出一个矩形形状,接着鼠标点击矩形,调整成无规则图形,在工具箱中选

photoshop教程:制作心形宝盒的发光动画

photoshop教程:制作心形宝盒的发光动画. 为照顾新朋友,教程写的比较详细,其实制作过程很简单,很适合初学者练习喔~ 先来看下效果: 素材: 1.首先打开PS,然后选择"文件--打开"打开素材图片   因为刚打开的素材图片是索引颜色的,不能编辑,所以,选择"图像--模式--RGB颜色" 现在图像可以用了,按Ctrl+J复制图层,出现图层1 2.现在要把中间的宝石盒单独抠出来,这是一张全黑背景的,所以非常好抠,直接用魔术棒就可以了.选择魔术棒工具,在黑色背景上点

PS教程:制作超酷的3D文字效果

Photoshop教程:制作超酷的3D文字效果,学好本教程以后大家可以尝试着做中文字哦-很炫的效果哟- 学好本教程以后大家可以尝试着做中文字哦-很炫的效果哟- 步骤1 首先,我们需要写3D文本.我们可以在illustrator中制作,或者点击下面的缩略图下载样本(如何制作3D效果文字在这里就不累述了): 步骤2 放置3D文字,并重命名为"3D text ".然后,用魔术棒工具选择字母的表面,剪切出这部分,你会看到下面的效果. 步骤3 现在到了有趣的部分了.把这层复制两份,一份用于备份(

Fireworks实例教程制作:燃烧效果制作

  现在FireworksMX新功能提供了很强的像素图处理能力,试着用其中的涂抹.淡化等工具制作燃烧效果,一样很不错.下文是Fireworks实例教程制作 :燃烧效果制作的范例,供大家参考学习. 制作步骤: 一.首先建立一个500X400的画布,因为需要涂抹,范围太小不好操作,填为黑色,如下图: 二.在制作燃烧文字之前,我们先练习制作一组火苗,这对理解火焰的走势有帮助.如下图,拖画三个椭圆形,分别填充为黄.橙.红色,调整大小位置,做下图的排列,这样形成焰芯.内焰.外焰的轮廓. 将它们群组,复制几

Excel制作颜色表示负值图标

  如图所示为某城市的月平均气温数据,需要用其制作一个条形图. Office教程 Excel制作颜色表示负值图标 1.选择数据区域中的某个单元格,在功能区中选择"插入"选项卡,在"图表"组中单击"条形图→簇状条形图". 2.双击图表中的数据系列,弹出"设置数据系列格式"对话框,选择"填充".在右侧区域中选择"纯色填充",并勾选"以互补色代表负值".这时下部的"