You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

双背景动画按钮改造:实现无需Hover触发的持续背景动画效果

实现持续运行的双背景动画按钮(仅用button元素)

我帮你调整了参考的Codepen代码,只需要修改几个关键CSS属性,就能让背景动画持续运行,不需要hover触发,而且完全只用button元素实现,不用嵌套div/span之类的标签。

关键修改点

  • 把伪元素:before的默认opacity0改成1,让渐变动画背景一开始就显示
  • 移除:hover:before的触发规则,因为不需要hover来激活动画
  • 删掉不必要的opacity过渡效果,避免多余的动画切换

修改后的完整代码

<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> 
<button class="glow-on-hover" type="button">持续动画按钮</button>
html, body { 
  margin: 0; 
  padding: 0; 
  width: 100%; 
  height: 100vh; 
  display: flex; 
  flex-direction: row; 
  justify-content: center; 
  align-items: center; 
  background: #000; 
} 

.glow-on-hover { 
  width: 220px; 
  height: 50px; 
  border: none; 
  outline: none; 
  color: #fff; 
  background: #111; 
  cursor: pointer; 
  position: relative; 
  z-index: 0; 
  border-radius: 10px; 
} 

.glow-on-hover:before { 
  content: ''; 
  background: linear-gradient(45deg, #ff0000, #ff7300, #fffb00, #48ff00, #00ffd5, #002bff, #7a00ff, #ff00c8, #ff0000); 
  position: absolute; 
  top: -2px; 
  left: -2px; 
  background-size: 400%; 
  z-index: -1; 
  filter: blur(5px); 
  width: calc(100% + 4px); 
  height: calc(100% + 4px); 
  animation: glowing 20s linear infinite; 
  /* 修改:默认显示动画背景 */
  opacity: 1; 
  /* 移除不必要的过渡 */
  border-radius: 10px; 
} 

.glow-on-hover:active { 
  color: #000 
} 

.glow-on-hover:active:after { 
  background: transparent; 
} 

.glow-on-hover:after { 
  z-index: -1; 
  content: ''; 
  position: absolute; 
  width: 100%; 
  height: 100%; 
  background: #111; 
  left: 0; 
  top: 0; 
  border-radius: 10px; 
} 

@keyframes glowing { 
  0% { background-position: 0 0; } 
  50% { background-position: 400% 0; } 
  100% { background-position: 0 0; } 
} 

原理说明

这个实现依然利用button的两个伪元素来实现双背景效果:

  • :before伪元素:负责展示渐变动画背景,通过filter: blur(5px)实现发光效果,并且设置了animation: glowing让渐变位置持续移动,默认opacity:1让它一直显示
  • :after伪元素:作为按钮的纯色背景,覆盖在:before之上,只留出:before的边缘部分(因为:before比按钮大4px),这样就形成了按钮边缘持续发光动画的效果

内容的提问来源于stack exchange,提问作者JuanFernandoz

火山引擎 最新活动