Skip to content

Commit

Permalink
fix(hexColorToRgba): opacity support string number
Browse files Browse the repository at this point in the history
  • Loading branch information
fupengl committed Jan 17, 2023
1 parent 9da4df1 commit be29e01
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 2 deletions.
3 changes: 3 additions & 0 deletions __tests__/color.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ describe('bom/color', () => {
it('hexColorToRgba', () => {
expect(hexColorToRgba('#000')).toBe('rgb(0,0,0)');
expect(hexColorToRgba('#000000')).toBe('rgb(0,0,0)');
expect(hexColorToRgba('#000000', 1)).toBe('rgba(0,0,0,1)');
expect(hexColorToRgba('#000000', '0.1')).toBe('rgba(0,0,0,0.1)');
expect(hexColorToRgba('#000000', 'a')).toBe('rgb(0,0,0)');
});

it('rgbaColorToHex', () => {
Expand Down
6 changes: 4 additions & 2 deletions src/dom/color.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isDigit } from '../is';

/**
* hex color 转化为 rgba
* @param hex
Expand All @@ -6,15 +8,15 @@
* @category Dom
* TODO support hex8
*/
export function hexColorToRgba(hex: string, opacity?: number) {
export function hexColorToRgba(hex: string, opacity?: number | string) {
let c: any;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length === 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = '0x' + c.join('');
if (typeof opacity !== 'number') {
if (!isDigit(opacity)) {
return `rgb(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')})`;
}
return `rgba(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')},${opacity})`;
Expand Down

0 comments on commit be29e01

Please sign in to comment.