当前位置:首页 > 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 样式:

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

vue实现点击涟漪

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

相关文章

vue实现聊天

vue实现聊天

Vue实现聊天功能 基础项目结构搭建 使用Vue CLI或Vite创建项目,安装必要依赖如socket.io-client或axios(根据通信方式选择)。核心组件通常包括: ChatWindow.…

vue双向实现

vue双向实现

Vue 双向数据绑定的实现原理 Vue 的双向数据绑定主要通过 v-model 指令实现,其核心是结合了数据劫持(Object.defineProperty 或 Proxy)和发布-订阅模式。 数…

vue 实现目录

vue 实现目录

Vue 实现目录的方法 在 Vue 项目中实现目录功能,可以通过以下几种方式实现,具体取决于需求和技术栈。 使用 Vue Router 实现路由目录 Vue Router 是 Vue.js 的官方…

vue实现文档分享

vue实现文档分享

Vue 实现文档分享功能 文档分享功能通常涉及文件上传、存储、生成分享链接以及权限控制等模块。以下是基于 Vue 的实现方案: 文件上传组件 使用 element-ui 或 ant-design-v…

vue实现视频开场

vue实现视频开场

使用 Vue 实现视频开场动画 在 Vue 中实现视频开场动画可以通过结合 HTML5 的 <video> 标签和 Vue 的过渡效果或生命周期钩子来完成。以下是具体实现方法: 安装依赖…

vue 页签实现

vue 页签实现

Vue 页签实现方法 在 Vue 中实现页签功能通常涉及动态组件、路由或状态管理。以下是几种常见的实现方式: 使用动态组件 通过 Vue 的 <component> 动态组件结合 v-…