css制作波纹
使用CSS制作波纹效果
通过CSS的animation和transform属性可以轻松实现波纹效果,以下是两种常见方法:
方法一:利用伪元素和scale动画
通过伪元素创建圆形背景,并用动画控制其缩放和透明度变化。
<div class="ripple-button">点击我</div>
.ripple-button {
position: relative;
overflow: hidden;
padding: 12px 24px;
background-color: #6200ea;
color: white;
border: none;
cursor: pointer;
}
.ripple-button::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
width: 5px;
height: 5px;
background: rgba(255, 255, 255, 0.5);
opacity: 0;
border-radius: 50%;
transform: translate(-50%, -50%) scale(1);
}
.ripple-button:active::after {
animation: ripple 0.6s ease-out;
}
@keyframes ripple {
to {
transform: translate(-50%, -50%) scale(20);
opacity: 0;
}
}
方法二:通过JavaScript动态添加波纹元素
结合CSS和JavaScript实现更灵活的交互效果。
<button class="js-ripple-button">点击触发波纹</button>
.ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.7);
transform: scale(0);
animation: ripple-animation 0.6s linear;
pointer-events: none;
}
@keyframes ripple-animation {
to {
transform: scale(4);
opacity: 0;
}
}
document.querySelector('.js-ripple-button').addEventListener('click', function(e) {
const ripple = document.createElement('span');
ripple.classList.add('ripple');
this.appendChild(ripple);
const rect = e.target.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
setTimeout(() => ripple.remove(), 600);
});
关键参数调整
- 颜色:通过
background-color修改波纹颜色。 - 大小:调整伪元素的初始
width/height或JavaScript中的scale值。 - 速度:修改
animation-duration(如0.6s)控制动画时长。 - 形状:
border-radius: 50%确保圆形波纹,可改为其他值实现不同形状。
浏览器兼容性
- 现代浏览器均支持此效果
- 如需兼容旧版浏览器,需添加
-webkit-前缀:@-webkit-keyframes ripple { ... }







