簡體   English   中英

jss如何改變顏色的不透明度

[英]jss how to change opacity for a color

目前我正在使用以下代碼使用 jss 為元素添加顏色。

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

我想知道是否存在基於顏色theme.colors.red添加不透明度的功能。

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

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)
}

對於 Mui v5:

import { alpha } from "@mui/material";

或者,您可以從 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/poliished的類似顏色函數

假設您還沒有在顏色中定義 alpha 通道,您還可以執行以下操作:

backgroundColor: theme.colors.red + '00' 

這會將 Alpha 通道設置為 0,因此是透明的。 您可以附加'00''ff'之間的任何值

我找到了一個解決方案

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

其中一些答案引用了已棄用的 Material-UI 函數。 當前首選的方法是使用alpha

import { alpha } from "@material-ui/core";

...
                 // yields rgba(255,255,255,0.85)
backgroundColor: alpha(theme.palette.background.paper, 0.85) 

您可以使用 RGBA 值

const styleSheet = theme => ({
  root: {
     backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
})

https://facebook.github.io/react-native/docs/colors.html

另一種可能是:

import color from "color"

const themeColorsRed = color
  .rgb(theme.colors.red)
  .array()

然后你可以這樣做:

{
  backgroundColor: `rgba(${themeColorsRed}, 0.05)`,
}

值得一提的是,8 位十六進制代碼也可以使用

const styleSheet = theme => ({
  root: {
     backgroundColor: '#ffffff80',
  },
})

對於 MUI v5,這似乎可行:

import { alpha } from '@mui/material';

...

MuiContainer: {
      styleOverrides: {
        root: {
          '&.MuiContainer-asideWithImage': {
            backgroundColor: alpha(MY_COLOR, 0.78),
          },
        },
      },
    },

...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM