Radex
Radex

Reputation: 8577

How to return rgba value from window.getComputedStyle() or other function?

I have a div with applied some inline style as rgba(0,255,0,1) and I am using ...style.borderColor to return a string with its color value.

I have noticed if alpha channel is 1 (no transparency) the value returned is only in rgb format, if instead color applied as some transparency like rgba(0,255,0,0.5) values is returned correctly in rgba.

var elm = document.querySelector('#target');
console.log(elm.style.borderColor);
<div id="target" style="  width: 150px;  height:150px;  background-color:red;  border-color: rgba(0,255,0,1);   border-width: 20px;   border-style: solid;"></div>

Upvotes: 4

Views: 1005

Answers (1)

Aruna
Aruna

Reputation: 12022

You can try the below generic method to parse them.

var elm1 = document.querySelector('#target1');
//console.log(parseColor(elm1.style.borderColor));
console.log(formatRGBA(elm1.style.borderColor));

var elm2 = document.querySelector('#target2');
//console.log(parseColor(elm2.style.borderColor));
console.log(formatRGBA(elm2.style.borderColor));

var elm3 = document.querySelector('#target3');
//console.log(parseColor(elm3.style.borderColor));
console.log(formatRGBA(elm3.style.borderColor));



function parseColor(color) {
  var m = color.match(/^rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/i);
  if( m) {
     return [m[1], m[2], m[3], '1'];
  }
  
  m = color.match(/^rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*((0.)?\d+)\s*\)$/i);
  if( m) {
     return [m[1], m[2], m[3], m[4]];
  }
}

function formatRGBA(color) {
  var component = parseColor(color);
  return 'rgba(' + component.join(',') + ')';
}
<div id="target1" style="  width: 150px;  height:150px;  background-color:red;  border-color: rgba(0,255,0,1);   border-width: 20px;   border-style: solid;"></div>
<div id="target2" style="  width: 150px;  height:150px;  background-color:red;  border-color: rgba(0,255,0,0);   border-width: 20px;   border-style: solid;"></div>
<div id="target3" style="  width: 150px;  height:150px;  background-color:red;  border-color: rgba(0,255,0,0.5);   border-width: 20px;   border-style: solid;"></div>

Upvotes: 4

Related Questions