css制作波纹
使用 CSS 制作波纹效果
方法一:利用 ::after 伪元素和动画
通过伪元素和 CSS 动画实现点击时的波纹扩散效果。

.ripple-button {
position: relative;
overflow: hidden;
padding: 12px 24px;
background-color: #6200ea;
color: white;
border: none;
border-radius: 4px;
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: 100%;
transform: translate(-50%, -50%) scale(1);
}
.ripple-button:active::after {
animation: ripple 0.6s ease-out;
}
@keyframes ripple {
0% {
transform: translate(-50%, -50%) scale(1);
opacity: 1;
}
100% {
transform: translate(-50%, -50%) scale(20);
opacity: 0;
}
}
方法二:通过 JavaScript 动态创建波纹元素
结合 JavaScript 动态创建波纹元素,实现更灵活的交互效果。

<button class="js-ripple-button">Click Me</button>
.js-ripple-button {
position: relative;
overflow: hidden;
padding: 12px 24px;
background-color: #6200ea;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.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.className = 'ripple';
this.appendChild(ripple);
const rect = this.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);
});
方法三:使用 CSS box-shadow 实现波纹
通过 box-shadow 和动画创建简单的波纹效果。
.box-ripple {
width: 100px;
height: 100px;
border-radius: 50%;
background: #03a9f4;
animation: box-ripple 1.5s infinite;
}
@keyframes box-ripple {
0% {
box-shadow: 0 0 0 0 rgba(3, 169, 244, 0.7);
}
70% {
box-shadow: 0 0 0 20px rgba(3, 169, 244, 0);
}
100% {
box-shadow: 0 0 0 0 rgba(3, 169, 244, 0);
}
}
注意事项
- 确保父容器设置了
position: relative和overflow: hidden,防止波纹扩散到容器外部 - 调整动画时间和缩放比例可以改变波纹扩散的速度和范围
- 使用
rgba()颜色值可以控制波纹的透明度效果 - 对于性能敏感的场景,考虑使用
transform而不是width/height动画
以上方法可以根据具体需求选择使用,纯 CSS 方案适合简单交互,JavaScript 方案则提供更精确的控制能力。






