[英]Parse CSS Color to RGBA values
我想從某些<color> CSS數據類型值中獲取RGBA值。
該函數應接受描述某種顏色的字符串,並返回具有紅色,綠色,藍色和alpha值的對象。
例如:
parseColor('red') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('#f00') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('rgb(255,0,0)') -> { red: 255, green: 0, blue: 0, alpha: 1 }
parseColor('hsla(0,100%,50%,0.1)') -> { red: 255, green: 0, blue: 0, alpha: 0.1 }
parseColor('transparent') -> { red: any_is_ok, green: any_is_ok, blue: any_is_ok, alpha: 0 }
因此,我嘗試了如下代碼:
function parseColor(color) {
var x = document.createElement('div');
document.body.appendChild(x);
var color, rgba;
var red = 0, green = 0, blue = 0, alpha = 0;
try {
x.style = 'color: ' + color + '!important';
color = window.getComputedStyle(x).color
rgba = color.match(/rgba?\((.*)\)/)[1].split(',').map(Number);
red = rgba[0];
green = rgba[1];
blue = rgba[2];
alpha = '3' in rgba ? rgba[3] : 1;
} catch (e) {
}
x.parentNode.removeChild(x);
return {'red': red, 'green': green, 'blue': blue, 'alpha': alpha};
}
它在Firefox,IE和Chrome中均可使用。 但是我不知道會返回什么window.getComputedStyle(x).color
? 此函數是否總是以rgb()
或rgba()
格式返回顏色? 規格說明了什么?
而且,還有其他方法可以實現parseColor
函數嗎?
parseColor
函數通過創建虛擬元素並為其設置顏色來工作,因此它可以在rgba()或rgb()中獲得顏色(取決於color
參數),但結果始終在rgba()中,因為
alpha = '3' in rgba ? rgba[3] : 1;
這意味着如果沒有alpha(a),它將設置為1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.