日期:2014-05-16 浏览次数:20431 次
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>颜色渐变</title> <script type="text/javascript"> var Color = { startColor : null, endColor : null, length: 0, space : null, init : function(startColor, endColor, length){ this.startColor = this.convertColor(startColor);; this.endColor = this.convertColor(endColor); this.length = length; if(this.startColor && this.endColor && length){ var rc = this.startColor, ec = this.endColor,len = length - (length > 1 ? 1 : 0); this.space = {R : (ec.R - rc.R) / len, G : (ec.G - rc.G) / len, B : (ec.B - rc.B) / len}; } }, convertColor : function(colorString){ if(/^#(\w{2})(\w{2})(\w{2})$/.test(colorString)){ return {R : parseInt(RegExp.$1, 16), G : parseInt(RegExp.$2, 16), B : parseInt(RegExp.$3, 16)}; } return null; }, format : function(n){ if(n < 0) n = 0; return ("0" + parseInt(n).toString(16)).slice(-2); }, getColor : function(current){ var rc = this.startColor, ec = this.endColor, s = this.space, color; if(!rc || !ec || !this.length){ return ""; } color = this.format(rc.R + s.R*current) + this.format(rc.G + s.G*current) + this.format(rc.B + s.B*current); return "#" + color; } }; window.onload = function(){ var box = document.getElementById("box"), sColor = "#FFFF00", eColor = "#FF0000", cur = 0, step = 100, interval = 100; Color.init(sColor, eColor, step); (function(){ box.style.backgroundColor = Color.getColor(cur); if(++cur < step){ setTimeout(arguments.callee, interval); } })(); }; </script> </head> <body> <div id="box" style="width:200px;height:200px; margin:100px auto;"></div> </body> </html>
------解决方案--------------------
CSS3渐变吧 -webkit-linear-gradient(diraction,startColor,endColor);
diraction:渐变的方向,top left right bottom
startColor和endColor是颜色,开始和结束的颜色,这样就渐变了。根据你的需要加前缀可以将webkit改成moz火狐的等等。。。。IE9不知道支持不 没有试过。然后参数通过JS根据时间动态传入就可以了