日期:2014-05-16  浏览次数:20431 次

如何根据时间控制颜色渐变呢?
需求是想要一个div块由黄变成红色,而这个转变的过程由具体时间来控制,可以想象成太阳,现在是正午所以是黄色,可是打了下午五六点就应该变成橘红色。。。能达到这种效果吗?

------解决方案--------------------
根据时间改变div 的背景就行了
------解决方案--------------------
颜色由RGB代码表示,可以根据时间慢慢的变化,如从#000000、#000001、#000002....#000009、#000010、#000001.....#FFFFFF
------解决方案--------------------

HTML code

<!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根据时间动态传入就可以了