简体   繁体   English

为什么渐变文本在 JavaScript 中不起作用?

[英]Why doesn't gradient text work in JavaScript?

I'm trying to make gradient text with javascript and CSS.我正在尝试使用 javascript 和 CSS 制作渐变文本。 The text is not showing, and if I remove -webkit-background-clip, the text is black, not gradient.文本没有显示,如果我删除 -webkit-background-clip,文本是黑色的,而不是渐变的。 Here is my code:这是我的代码:

 let gradientText = document.getElementById('title'); gradientText.style.background = '-webkit-linear-gradient(#ccc, #000)';
 #title { font-size:40px; -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
 <h1 id="title">Gradient text</h1>

It seems you've got your rules applied a bit out-of-order.似乎您的规则应用有点乱。 Set the background property before setting the background clipping and text fill colors:在设置背景剪裁和文本填充颜色之前设置background属性:

 #title { background: -webkit-linear-gradient(#ccc, #000); font-size:40px; -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
 <h1 id="title">Gradient text</h1>

You have also set the webKitBackgroundClip in your js code to make it work:您还在 js 代码中设置了 webKitBackgroundClip 以使其工作:

 let gradientText = document.getElementById('title'); gradientText.style.background = '-webkit-linear-gradient(#eee, #333)'; gradientText.style.webkitBackgroundClip = 'text'; // this is important
 #title { background: -webkit-linear-gradient(#ccc, #000); font-size:40px; -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
 <h1 id="title">Gradient text</h1>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM