How to get hex color value rather than RGB value?

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

    Here's an ES6 one liner that doesn't use jQuery:

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

提交回复
热议问题