utils.parseColor = function (color, toNumber) {
if (toNumber === true) {
if (typeof color === 'number') {
return (color | 0); //chop off decimal
}
if (typeof color === 'string' && color[0] === '#') {
color = color.slice(1);
}
return window.parseInt(color, 16);
} else {
if (typeof color === 'number') {
//make sure our hexadecimal number is padded out
color = '#' + ('00000' + (color | 0).toString(16)).substr(-6);
}
return color;
}
};
嘿,夥計們,我遇到這段代碼。它是JavaScript中的一個實用功能,可以在數字和字符串之間來回轉換顏色。有2個部分我不太確定,Javascript - 轉換顏色(數字 - >字符串)反之亦然
首先, return (color|0);
是什麼意思?什麼是|
?在JavaScript中?
其次,在該行
color = '#' + ('00000' + (color | 0).toString(16)).substr(-6);
爲什麼我需要確保十六進制數被填充?我們想在這裏實現什麼?
調用像utils.parseColor(0xFFFF00)
用十六進制數的函數,返回字符串 值:"#ffff00"
。傳遞CSS樣式的十六進制字符串將返回未修改的相同字符串。 函數還接受第二個可選參數toNumber
,如果設置爲true
,則返回數值 顏色值。例如,撥打utils.parseColor("#FFFF00", true)
或 utils.parseColor(0xFFFF00, true)
,兩者均返回號碼16776960
。
謝謝, 維恩。
這個答案! Tikhon幹得好! – 2016-04-14 12:18:00