RGB to hex and hex to RGB

前端 未结 30 2840
遥遥无期
遥遥无期 2020-11-21 06:56

How to convert colors in RGB format to hex format and vice versa?

For example, convert \'#0080C0\' to (0, 128, 192).

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 07:26

    This could be used for getting colors from computed style propeties:

    function rgbToHex(color) {
        color = ""+ color;
        if (!color || color.indexOf("rgb") < 0) {
            return;
        }
    
        if (color.charAt(0) == "#") {
            return color;
        }
    
        var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
            r = parseInt(nums[2], 10).toString(16),
            g = parseInt(nums[3], 10).toString(16),
            b = parseInt(nums[4], 10).toString(16);
    
        return "#"+ (
            (r.length == 1 ? "0"+ r : r) +
            (g.length == 1 ? "0"+ g : g) +
            (b.length == 1 ? "0"+ b : b)
        );
    }
    
    // not computed 
    
    ...
    // computed
    ...
    console.log( rgbToHex(color) ) // #4d93bc console.log( rgbToHex(borderTopColor) ) // #ff0000

    Ref: https://github.com/k-gun/so/blob/master/so_util.js

提交回复
热议问题