简体   繁体   中英

Why doesn't gradient text work in JavaScript?

I'm trying to make gradient text with javascript and CSS. The text is not showing, and if I remove -webkit-background-clip, the text is black, not gradient. 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:

 #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:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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