如何将CSS按钮的Hover发光动画改为持续生效?
实现按钮持续发光动画的修改方案
现有代码通过:hover触发按钮的发光动画,要实现无需hover操作就让发光效果持续生效,只需调整伪元素的opacity属性即可,具体修改步骤如下:
- 找到
.drts-bs-btn-outline-primary:before规则,将其中的opacity: 0改为opacity: 1 - 可删除
.drts-bs-btn-outline-primary:hover:before规则(不再需要hover触发),保留也不会影响最终效果
修改后的完整代码:
.drts-bs-btn-outline-primary { width: 220px; height: 50px; border: none; outline: none; color: #fff; background: #111; cursor: pointer; position: relative; z-index: 0; border-radius: 10px; } .drts-bs-btn-outline-primary: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; /* 此处修改为1 */ transition: opacity .3s ease-in-out; border-radius: 10px; } .drts-bs-btn-outline-primary:active { color: #000 } .drts-bs-btn-outline-primary:active:after { background: transparent; } /* 可删除该hover规则,也可保留 */ /* .drts-bs-btn-outline-primary:hover:before { opacity: 1; } */ .drts-bs-btn-outline-primary: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; } }
原理说明
原本的发光动画glowing其实一直处于运行状态,只是:before伪元素默认opacity: 0所以不可见。hover触发时只是将opacity改为1显示效果,直接把opacity设为1就能让发光效果始终展示,无需hover操作触发。
内容的提问来源于stack exchange,提问作者CcCcSS
相关产品推荐
相关产品推荐

