How to get hex color value rather than RGB value?

前端 未结 19 3162
猫巷女王i
猫巷女王i 2020-11-21 23:06

Using the following jQuery will get the RGB value of an element\'s background color:

$(\'#selector\').css(\'backgroundColor\');

Is there a

19条回答
  •  日久生厌
    2020-11-21 23:14

    Just to add to @Justin's answer above..

    it should be

    var rgb = document.querySelector('#selector').style['background-color'];
    return '#' + rgb.substr(4, rgb.indexOf(')') - 4).split(',').map((color) => String("0" + parseInt(color).toString(16)).slice(-2)).join('');
    

    As the above parse int functions truncates leading zeroes, thus produces incorrect color codes of 5 or 4 letters may be... i.e. for rgb(216, 160, 10) it produces #d8a0a while it should be #d8a00a.

    Thanks

提交回复
热议问题