vue实现点击涟漪
Vue 实现点击涟漪效果
在 Vue 中实现点击涟漪效果可以通过自定义指令或使用第三方库完成。以下是两种常见方法:
自定义指令实现
创建自定义指令 v-ripple,动态生成涟漪元素并添加动画效果:
// 在 main.js 或单独指令文件中
Vue.directive('ripple', {
inserted(el) {
el.style.position = 'relative'
el.style.overflow = 'hidden'
el.addEventListener('click', (e) => {
const ripple = document.createElement('span')
ripple.className = 'ripple-effect'
const rect = el.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.width = ripple.style.height = `${size}px`
ripple.style.left = `${x}px`
ripple.style.top = `${y}px`
el.appendChild(ripple)
setTimeout(() => {
ripple.remove()
}, 600)
})
}
})
添加对应 CSS 样式:
.ripple-effect {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.7);
transform: scale(0);
animation: ripple 0.6s linear;
pointer-events: none;
}
@keyframes ripple {
to {
transform: scale(2);
opacity: 0;
}
}
使用第三方库
安装 vue-ripple-directive 库:
npm install vue-ripple-directive
在项目中引入并使用:
import VueRipple from 'vue-ripple-directive'
Vue.use(VueRipple)
在组件中使用:
<button v-ripple>点击按钮</button>
自定义涟漪效果参数
通过指令参数可以自定义涟漪颜色和持续时间:
Vue.directive('ripple', {
inserted(el, binding) {
const color = binding.value?.color || 'rgba(255, 255, 255, 0.7)'
const duration = binding.value?.duration || 600
// ...其余实现代码...
}
})
使用时传递参数:
<button v-ripple="{ color: 'rgba(0, 150, 136, 0.3)', duration: 800 }">
自定义涟漪
</button>
注意事项
- 确保目标元素设置了
position: relative和overflow: hidden - 移动端设备需要添加
touchstart事件监听 - 动态生成的内容需要重新绑定指令
- 性能优化:避免频繁创建 DOM 元素,可考虑对象池技术







