jss如何改变颜色的不透明度

IT技术 javascript reactjs material-ui jss
2021-05-11 14:12:21

目前我正在使用以下代码为使用 jss 的元素添加颜色。

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})

我想知道是否存在基于颜色添加不透明度的函数theme.colors.red

示例 smt 喜欢: backgroundColor: color(theme.colors.red, .05),

4个回答

Material UI 有一个colorManipulator 实用程序文件,其中包含一个alpha功能:

import { alpha } from '@material-ui/core/styles/colorManipulator';

/**
 * Sets the absolute transparency of a color.
 * Any existing alpha values are overwritten.
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
 * @param {number} value - value to set the alpha channel to in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

{
    backgroundColor: alpha(theme.colors.red, 0.5)
}

或者,您可以从 npm添加颜色库以进行颜色操作:

import Color from 'color';

{
    backgroundColor: Color(theme.colors.red).alpha(0.5).string()
}

或者,您可以使用 Material UI Next 中提供的淡入淡出功能。

import {fade} from 'material-ui/styles/colorManipulator';

const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        boxShadow: `0 4px 8px 0 ${fade(defaultTheme.palette.primary[500], 0.18)}`,
      }
    },
  }
});

export default theme;

这是它的工作原理:https : //github.com/mui-org/material-ui/blob/v1-beta/src/styles/colorManipulator.js#L157-L164

另一种解决方案可能是使用来自https://github.com/styled-components/polished 的类似颜色函数

假设您还没有在颜色中定义 alpha 通道,您还可以执行以下操作:

backgroundColor: theme.colors.red + '00' 

这会将 alpha 通道设置为 0,因此是透明的。您可以在'00'之间附加任何值'ff'

我找到了一个解决方案

 backgroundColor: theme.utils.rgba(theme.axColor.black, 0.7),