[JS]颜色渐变

/*
参数:
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;
};
原文链接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值