水波纹效果通过CSS动画和JS点击坐标实现,核心是创建圆形元素从点击位置扩散。使用相对定位按钮,动态生成带ripple-effect动画的span,设置渐隐放大效果,并在动画结束后移除元素,适用于Material风格界面,注意控制颜色、尺寸与动画时长以提升交互体验。

按钮点击时的水波纹效果(也叫涟漪效果)在 Material Design 中很常见,能增强用户交互反馈。通过 CSS 和少量 JavaScript 可以轻松实现这一效果。
水波纹效果的核心是在按钮内部创建一个圆形的 ::after 或动态 span 元素,点击时从点击位置向外扩散并逐渐透明消失。
虽然不能完全不用 JS 获取点击坐标,但 CSS 负责动画和样式,JS 仅添加类或元素。
立即学习“前端免费学习笔记(深入)”;
HTML 结构:
<button class="ripple-btn">点击我</button>
立即学习“前端免费学习笔记(深入)”;
CSS 样式:
.ripple-btn {
position: relative;
overflow: hidden;
padding: 12px 24px;
font-size: 16px;
color: white;
background-color: #007bff;
border: none;
border-radius: 4px;
cursor: pointer;
}
.ripple-btn::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
width: 0;
height: 0;
background-color: rgba(255, 255, 255, 0.5);
border-radius: 50%;
opacity: 0;
transition: opacity 1s ease-out, transform 1s ease-out, width 1s ease-out, height 1s ease-out;
pointer-events: none;
}
.ripple-btn:active::after {
width: 200px;
height: 200px;
opacity: 1;
transform: translate(-50%, -50%) scale(1);
}上面的方式中心扩散,不够真实。可以通过 JS 动态创建波纹元素,从实际点击位置展开。
立即学习“前端免费学习笔记(深入)”;
改进版 JS + CSS:
document.querySelectorAll('.ripple-btn').forEach(button => {
button.addEventListener('click', function (e) {
const ripple = document.createElement('span');
const rect = this.getBoundingClientRect();
const size = Math.max(rect.width, rect.height);
const x = e.clientX - rect.left - size / 2;
const y = e.clientY - rect.top - size / 2;
ripple.style.cssText = `
position: absolute;
width: ${size}px;
height: ${size}px;
left: ${x}px;
top: ${y}px;
background-color: rgba(255, 255, 255, 0.4);
border-radius: 50%;
transform: scale(0);
animation: ripple-effect 0.6s ease-out;
pointer-events: none;
`;
this.appendChild(ripple);
setTimeout(() => {
ripple.remove();
}, 600);
});
});立即学习“前端免费学习笔记(深入)”;
对应的关键帧动画 CSS:
@keyframes ripple-effect {
to {
transform: scale(2);
opacity: 0;
}
}这类效果适合用在扁平化或 Material 风格的界面中。注意以下几点:
基本上就这些,不复杂但容易忽略细节。
以上就是如何通过css制作按钮点击水波纹效果的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号