How to get hex color value rather than RGB value?

前端 未结 19 3168
猫巷女王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:36

    Steven Pribilinskiy's answer drops leading zeroes, for example #ff0000 becomes #ff00.

    A solution is to append a leading 0 and substring off the last 2 digits.

    var rgb = $('#selector').css('backgroundColor').match(/\d+/g);
    var hex = '#'+ String('0' + Number(rgb[0]).toString(16)).slice(-2) + String('0' + Number(rgb[1]).toString(16)).slice(-2) + String('0' + Number(rgb[2]).toString(16)).slice(-2);
    

提交回复
热议问题