文字颜色渐变
在我上一篇文章中提到了文字渐变色效果:文字渐变色填充,在填充时,我们也可以给样式增加部分JS功能,让颜色动起来。
文字颜色渐变
文字整体颜色随机渐变:
代码实现
<style>
.hellow-text {
font-size: 100px;
font-weight: bold;
background: linear-gradient(to right, red, blue, violet);
-webkit-background-clip: text;
color: transparent;
}
</style>
<body>
<div class="hellow-text" id="hellowText">文字颜色渐变</div>
</body>
<script>
function updateGradient() {
const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
// 随机生成3种颜色
const randomColor1 = colors[Math.floor(Math.random() * colors.length)];
const randomColor2 = colors[Math.floor(Math.random() * colors.length)];
const randomColor3 = colors[Math.floor(Math.random() * colors.length)];
// 获取hellowText元素
const hellowText = document.getElementById('hellowText');
// 重新设置hellowText的backgroundImage属性
hellowText.style.backgroundImage = `linear-gradient(to right, ${randomColor1}, ${randomColor2}, ${randomColor3})`;
}
// 设置定时器,每秒更新一次渐变颜色
setInterval(updateGradient, 1000);
</script>
效果预览

文字颜色跑马灯
除了上述颜色整体变换以外,我们也可以让颜色在水平方向移动,实现颜色跑马灯的效果:
代码实现
<style>
.hellow-text {
font-size: 86px;
font-weight: bold;
color: transparent;
-webkit-background-clip: text;
background-image: linear-gradient(90deg, red, orange, yellow, green, blue, indigo, violet);
/* 确保渐变图像有足够的空间在元素内移动 */
background-size: 200% 100%;
/* 线性移动,无限循环 */
animation: gradient-marquee 10s linear infinite;
}
@keyframes gradient-marquee {
/* 动画开始时刻 */
0% {
background-position: 100% 50%;
}
/* 动画结束时刻 */
100% {
background-position: 0% 50%;
}
}
</style>
<body>
<div class="hellow-text">渐变颜色跑马灯</div>
</body>
效果预览

结语
通过本文的介绍,相信你已经掌握了如何使用CSS+JS实现文字颜色渐变和文字跑马灯效果。希望这些技巧能帮助你提升网页设计的视觉效果。如果你有任何问题或建议,欢迎在评论区留言分享!
822

被折叠的 条评论
为什么被折叠?



