当前位置:首页 > 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实现微博发布动态

vue实现微博发布动态

使用Vue实现微博发布动态功能 创建Vue组件结构 新建一个WeiboPost.vue组件,包含文本框、图片上传和发布按钮: <template> <div class="we…

vue实现积分

vue实现积分

Vue 实现积分功能 在 Vue 中实现积分功能通常涉及前端展示、交互逻辑以及与后端 API 的通信。以下是常见的实现方法和步骤: 积分展示组件 创建一个积分展示组件,用于显示当前用户的积分。可以使…

vue实现管道

vue实现管道

Vue 中实现管道(Pipe)功能 在 Vue 中可以通过过滤器(Filters)或计算属性(Computed Properties)实现类似管道的功能,将数据经过多个处理步骤后输出。 使用过滤器(…

vue拖拽实现

vue拖拽实现

Vue 拖拽实现方法 使用 HTML5 原生拖拽 API HTML5 提供了原生拖拽 API,可以通过 draggable 属性、dragstart、dragend、dragover 和 drop 事…

vue实现tree

vue实现tree

Vue 实现 Tree 组件 使用 Vue 实现 Tree 组件可以通过递归组件的方式来实现层级结构展示。以下是一个完整的实现方法: 基础递归组件实现 创建 Tree 组件文件 Tree.vue,使…

vue实现分栏

vue实现分栏

Vue实现分栏的常见方法 使用CSS Flexbox布局 通过Flexbox可以快速实现分栏效果,适合大多数响应式布局场景 <template> <div class="con…