当前位置:首页 > VUE

vue实现点击涟漪

2026-01-08 14:51:24VUE

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 样式:

vue实现点击涟漪

.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

在项目中引入并使用:

vue实现点击涟漪

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: relativeoverflow: hidden
  • 移动端设备需要添加 touchstart 事件监听
  • 动态生成的内容需要重新绑定指令
  • 性能优化:避免频繁创建 DOM 元素,可考虑对象池技术

标签: 涟漪vue
分享给朋友:

相关文章

实现 vue ssr

实现 vue ssr

Vue SSR 实现方法 Vue SSR(Server-Side Rendering)通过服务器端渲染 Vue 应用,提升首屏加载速度和 SEO 友好性。以下是核心实现方法: 基础配置 安装必要依赖…

vue实现效果

vue实现效果

以下是Vue实现常见效果的几种典型方法,分为不同场景说明: 数据绑定与响应式更新 使用v-model实现表单双向绑定: <template> <input v-model="…

vue实现换行

vue实现换行

Vue 中实现换行的几种方法 在 Vue 中实现换行可以通过多种方式,具体取决于使用场景和需求。以下是常见的几种方法: 使用 HTML 的 <br> 标签 在模板中直接使用 <br…

vue实现mouseout

vue实现mouseout

Vue 实现 mouseout 事件的方法 在 Vue 中实现 mouseout 事件可以通过多种方式完成,以下是几种常见的方法: 使用 v-on 指令 Vue 提供了 v-on 指令(或简写为 @…

vue 实现脚本

vue 实现脚本

Vue 实现脚本的方法 Vue.js 提供了多种方式来实现脚本功能,包括组件内脚本、混入(Mixins)、插件(Plugins)以及自定义指令等。以下是常见的实现方式: 组件内脚本 在 Vue 单文…

vue实现预渲染

vue实现预渲染

vue实现预渲染的方法 预渲染(Prerendering)是指在构建阶段生成静态HTML文件,适用于内容变化较少且需要提升SEO和首屏加载速度的场景。Vue项目可通过以下方法实现预渲染: 使用pre…