渐变文本颜色,使用Material-UI的<Typography />。

6

如何为<Typography />组件设置渐变的font-color样式?

目前我尝试过的方法:

const CustomColor = withStyles({
  root: {
    fontColor: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
  },
})(Typography);

这样不起作用,所以我尝试按照教程操作,并进行了以下实现:

const CustomColor = withStyles({
  root: {
    fontSize: 20,
    background: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    webkitBackgroundClip: "text",
    WebkitTextFillColor: "transparent",
  },
})(Typography);

这种方法并没有达到预期的效果,但是至少展现了某种渐变色。 enter image description here 另一种我尝试过的方法是:
<Typography style={{
    fontSize: 20,
    background: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    webkitBackgroundClip: "text",
    WebkitTextFillColor: "transparent",
  }}> Hello world! </Typography>

这种方法有点可行,但是根据元素的宽度不同,渐变会发生变化。这是一个不希望出现的行为。另外我想坚持使用 withStyles 样式解决方案。
在线演示: 在这里 有什么提示吗?我错过了什么吗?

1
需要注意的第一件事是,渐变是CSS中的“特殊类型”图像,而不是颜色。例如,请参见链接https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient()。您能否提供一个有效的代码片段,以便我们可以看到问题,并进一步描述“未按预期工作”的含义。 - A Haworth
一张图片?还是你指的是整段代码? - Laczkó Örs
提供一个可以运行的代码,以展示您的问题。请使用SO片段系统。 - A Haworth
我正在尝试插入一个工作模板,但我必须承认,我不知道如何将我的“React”和“Material-UI”项目上传到SO。 - Laczkó Örs
1
@BudaÖrs 试着建立一个CodeSandbox或其他类似的代码共享/协作系统,并在此处分享它。 - jharris711
感谢您提供如此棒的建议! - Laczkó Örs
3个回答

9

webkitBackgroundClip替换为WebkitBackgroundClip。 JSS使用大写字母来表示webkit。

const CustomColor = withStyles({
  root: {
    fontSize: 20,
    background: "-webkit-linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
    WebkitBackgroundClip: "text",
    WebkitTextFillColor: "transparent"
  }
})(Typography);

这是工作演示:
Edit sad-star-v8u37


3
在花费一些时间尝试后,我想出了这个解决方案...
  <Typography
  variant="h1"
  align="left"
  color="grey.700"
  sx={{
    backgroundcolor: "primary",
    backgroundImage: `linear-gradient(45deg, #5514B4, #FF80FF)`,
    backgroundSize: "100%",
    backgroundRepeat: "repeat",
    backgroundClip: "text",
    WebkitBackgroundClip: "text",
    WebkitTextFillColor: "transparent"
  }}
>
  GRADIENT TEXT
</Typography>   

Codesandbox示例


0

我在使用MUI时遇到了问题,但是通过这种方法我解决了它。关键是使用backgroundImage而不是background。

WebkitBackgroundClip: 'text',
WebkitTextFillColor: 'transparent',
backgroundImage: '-webkit-linear-gradient(rgba(222, 53, 76, 0.8), rgba(226, 123, 27, 0.8))',

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接