答案:通过JavaScript捕获点击事件,在点击位置创建带缩放动画的圆形元素实现波纹效果。具体步骤为:1. 为按钮添加relative定位和overflow:hidden;2. 点击时获取相对于按钮的坐标x、y;3. 创建span元素并添加ripple类;4. 设置left、top定位至点击点;5. 利用CSS动画从scale(0)过渡到scale(4)并透明消失;6. 动画结束后移除元素防止内存泄漏;7. 可通过data属性自定义颜色,封装函数复用逻辑。该方法符合Material Design交互风格,关键在于坐标计算准确和DOM及时清理。

实现页面元素的波纹点击效果,可以通过 JavaScript 捕获点击事件,在点击位置动态创建一个带有动画效果的“波纹”元素。这种效果常见于 Material Design 风格的按钮交互中。下面介绍具体实现方法。
波纹效果的核心思路是:
<button class="ripple-btn">点击我</button>
先为波纹效果编写必要的样式:
.ripple-btn {
position: relative;
overflow: hidden;
padding: 12px 24px;
border: none;
background: #2196F3;
color: white;
border-radius: 4px;
cursor: pointer;
}
<p>.ripple {
position: absolute;
border-radius: 50%;
background: rgba(255, 255, 255, 0.7);
transform: scale(0);
animation: ripple-effect 0.6s linear;
}</p><p>@keyframes ripple-effect {
to {
transform: scale(4);
opacity: 0;
}
}</p>添加事件监听并动态生成波纹元素:
document.querySelectorAll('.ripple-btn').forEach(button => {
button.addEventListener('click', function(e) {
// 获取点击相对于元素的位置
const rect = this.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
<pre class='brush:php;toolbar:false;'>// 创建波纹元素
const ripple = document.createElement('span');
ripple.classList.add('ripple');
ripple.style.left = x + 'px';
ripple.style.top = y + 'px';
// 清除旧的波纹(可选)
this.querySelectorAll('.ripple').forEach(r => r.remove());
// 添加到按钮内
this.appendChild(ripple);
// 动画结束后移除元素
setTimeout(() => {
ripple.remove();
}, 600);}); });
基本上就这些。只要掌握事件坐标计算和动态元素动画插入,就能轻松实现流畅的波纹点击效果。不复杂但容易忽略细节,比如定位方式和动画结束清理。
以上就是js脚本如何实现页面元素波纹点击效果_js波纹动画脚本编写方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号