rgba和hex之间转换

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 19:20   2429   0

分享颜色插件【1:spectrum:https://www.bootcdn.cn/spectrum/ 2:官网:http://bgrins.github.io/spectrum/

1、hex转rgba

参考网站:https://blog.csdn.net/jyao_in/article/details/80615474

var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
String.prototype.colorRgb = function(){  
    var sColor = this.toLowerCase();  
    if(sColor && reg.test(sColor)){  
        if(sColor.length === 4){  
            var sColorNew = "#";  
            for(var i=1; i<4; i+=1){  
                sColorNew += sColor.slice(i,i+1).concat(sColor.slice(i,i+1));     
            }  
            sColor = sColorNew;  
        }
        var sColorChange = [];  
        for(var i=1; i<7; i+=2){  
            sColorChange.push(parseInt("0x"+sColor.slice(i,i+2)));    
        }
        return {red: sColorChange[0], green: sColorChange[1], blue: sColorChange[2], alpha: null}; 
    }else{  
        return sColor;
    }  
}
var color = '#ffffff';
color.colorRgb() // {red: 255, green: 255, blue: 255, alpha: null} (alpha自己添加进去的)

2、rgba转hex

参考网站:https://www.youyong.top/article/1159366a4e3b0

function colorHex(value) {
    if(!value) return '#ffffff';
    if(!isObj(value) && value.includes('#')) return value;
    var sColor = [value.red.toString(),value.green.toString(),value.blue.toString()];
    value = '';
    sColor.map(v => {
        v = parseInt(v.replace(/[^\d]/gi, ''), 10).toString(16);
        console.log(v.length == 1 ? "0" + v : v);
        value += v.length == 1 ? '0'+v : v;
    }).join('');
    return '#'+ value;
}
var obj = {red: 255, green: 255, blue: 255, alpha: null}
colorHex(obj)  // #ffffff

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP