CSS+JS实现文字渐变/文字跑马灯效果

文字颜色渐变

在我上一篇文章中提到了文字渐变色效果:文字渐变色填充,在填充时,我们也可以给样式增加部分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实现文字颜色渐变和文字跑马灯效果。希望这些技巧能帮助你提升网页设计的视觉效果。如果你有任何问题或建议,欢迎在评论区留言分享!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值