How to extract r, g, b, a values from CSS color?

后端 未结 7 483
猫巷女王i
猫巷女王i 2021-01-08 00:54

What would be the easiest way to transform

$(\'#my_element\').css(\'backgroundColor\')

to object like this:

{ r: red_value,         


        
相关标签:
7条回答
  • 2021-01-08 01:21
    var c = $('body').css('background-color');
    var rgb = c.replace(/^(rgb|rgba)\(/,'').replace(/\)$/,'').replace(/\s/g,'').split(',');
    
    for(var i in rgb) {
      console.log(rgb[i]);
    }
    

    Try it here http://jsbin.com/uhawa4

    Edit :

    var c = $('body').css('background-color');
    var rgb = c.replace(/^rgba?\(|\s+|\)$/g,'').split(',');
    
    for(var i in rgb) {
      console.log(rgb[i]);
    }
    

    or even simpler way, just aiming at numbers

    var c = 'rgba(60,4,2,6)';
    var rgb = c.match(/\d+/g);
    
    for(var i in rgb) {
      console.log(rgb[i]);
    }
    
    0 讨论(0)
提交回复
热议问题