解析字符串css样式
const themeColor = ` --btn-radius: 44rpx;--theme-color: #41c2a6;--theme-color-op: rgba(55, 176, 172, 0.3); `
const getThemeColor = ( themeColor, key ) => { const reg = new RegExp ( ` ${ key} :(.+?)\; ` ) ; const themeColorStr = themeColor. match ( reg) [ 0 ] const newStr = themeColorStr. slice ( key. length + 1 , themeColorStr. length - 1 ) return newStr. trim ( )
} getThemeColor ( themeColor, '--theme-color' )
rgb转换为hex
const setRgbTo16 = ( str ) => { if ( str. includes ( '#' ) ) { return str} let reg = / ^(rgb|RGB) / ; if ( ! reg. test ( str) ) { return ; } var arr = str. slice ( 4 , str. length- 1 ) . split ( "," ) let color = '#' ; for ( var i= 0 ; i< arr. length; i++ ) { var t = Number ( arr[ i] ) . toString ( 16 ) if ( t == "0" ) { t = t + "0" } color += t; } return color;
}
hex转换为rgba
function hexToRgba ( hex, alpha ) { alpha = Math. max ( 0 , Math. min ( alpha, 1 ) ) ; hex = hex. replace ( '#' , '' ) ; if ( hex. length === 3 ) { hex = hex[ 0 ] + hex[ 0 ] + hex[ 1 ] + hex[ 1 ] + hex[ 2 ] + hex[ 2 ] ; } const r = parseInt ( hex. slice ( 0 , 2 ) , 16 ) ; const g = parseInt ( hex. slice ( 2 , 4 ) , 16 ) ; const b = parseInt ( hex. slice ( 4 , 6 ) , 16 ) ; return ` rgba( ${ r} , ${ g} , ${ b} , ${ alpha. toFixed ( 2 ) } ) ` ;
}
const rgbaString = hexToRgba ( '#ff0000' , 0.5 ) ;
console. log ( rgbaString) ;