[JS]颜色渐变

来源:互联网 发布:oracle.sql.rowid 编辑:程序博客网 时间:2024/06/12 00:59
/*参数:obj:目标对象thisRGB:当前背景颜色的6位代码toRGB:目标背景颜色的6位代码thisColor:当前文字颜色的6位代码toColor:目标文字颜色的6位代码step:执行次数speed:执行速度*/function colorGradient(obj,thisRGB,toRGB,thisColor,toColor,step,speed){    var _thisRGB=colorConversion(thisRGB); //16进制转换10进制    var _toRGB=colorConversion(toRGB);    if(thisColor&&toColor){        var _thisColor=colorConversion(thisColor,1);        var _toColor=colorConversion(toColor,1);    }        var step=step?step:3;    var _step=step;    var _speed=speed?parseInt(speed/step):30;  //根据总时间计算每次执行的速度    var _R_step=parseInt(Math.abs(_thisRGB[0]-_toRGB[0])/_step);    var _G_step=parseInt(Math.abs(_thisRGB[1]-_toRGB[1])/_step);    var _B_step=parseInt(Math.abs(_thisRGB[2]-_toRGB[2])/_step);    var timer=setInterval(function(){        if(_step>0){            var s=(step-_step)+1;            var r=_step==1?_toRGB[0]:(_thisRGB[0]>_toRGB[0]?_thisRGB[0]-_R_step*s:_thisRGB[0]+_R_step*s);            var g=_step==1?_toRGB[1]:(_thisRGB[1]>_toRGB[1]?_thisRGB[1]-_G_step*s:_thisRGB[1]+_G_step*s);            var b=_step==1?_toRGB[2]:(_thisRGB[2]>_toRGB[2]?_thisRGB[2]-_B_step*s:_thisRGB[2]+_B_step*s);            obj.css({'background-color':'rgb('+r+','+g+','+b+')'});            if(thisColor&&toColor){                var cr=_step==1?_toColor[0]:(_thisColor[0]>_toColor[0]?_thisColor[0]-_R_step*s:_thisColor[0]+_R_step*s);                var cg=_step==1?_toColor[1]:(_thisColor[1]>_toColor[1]?_thisColor[1]-_G_step*s:_thisColor[1]+_G_step*s);                var cb=_step==1?_toColor[2]:(_thisColor[2]>_toColor[2]?_thisColor[2]-_B_step*s:_thisColor[2]+_B_step*s);                obj.css({'color':'rgb('+cr+','+cg+','+cb+')'});            }            _step--;        }else{            clearInterval(timer);            return true;        }    },_speed);}function colorConversion(code){    var len=code.length;    var f=new Array();    f['0']=0;    f['1']=1;    f['2']=2;    f['3']=3;    f['4']=4;    f['5']=5;    f['6']=6;    f['7']=7;    f['8']=8;    f['9']=9;    f['A']=10;    f['B']=11;    f['C']=12;    f['D']=13;    f['E']=14;    f['F']=15;    code=code.toLocaleUpperCase();//转换为大写    var s=code.substr(0,1);    if(s=='#'){        code=code.substr(1,6);    }    var r=f[code[0]]*16+f[code[1]];    var g=f[code[2]]*16+f[code[3]];    var b=f[code[4]]*16+f[code[5]];    return [r,g,b];}HTMLElement.prototype.css = function () {var option;if (arguments.length > 0) {option = arguments[0];if (2 === arguments.length) {option = {}, option[arguments[0]] = arguments[1];}if ('object' === typeof option) {for (var key in option) {if (option.hasOwnProperty(key)) {this.style[key] = option[key];}}}}return this;};
原文链接
原创粉丝点击