• Vue如何实现动画按钮效果?
  • 发布于 2个月前
  • 221 热度
    0 评论
前言
最近在看一些组件库的时候,发现他们有一种效果还挺好看的,就是点击会有水波效果~

所以就想写一个 Vue 的自定义指令指令来实现这个效果:v-ripple

使用方式是这样的:
<Button v-ripple>我是一个按钮</Button>

实现思路
思路就是,点击了按钮某一处时,往按钮dom中插入一个圆dom,这个圆dom是相对于按钮去定位的,坐标就是(x1,y1),至于(x1,y1)要怎么去算呢?其实很简单啊:
1、先算出鼠标点击相对于按钮的坐标(x,y)
2、(x-半径,y-半径) -> (x1,y1)
至于(x,y)要怎么算?也很简单啊(用到getBoundingClientRect)
1、算出鼠标点击的全局坐标
2、算出按钮的全局坐标
3、鼠标按钮坐标减去按钮坐标,就能得到(x,y)

开始实现
首先我们准备好基础的样式
// 堆代码 duidaima.com
// ripple.less
#ripple {
  position: absolute;
  pointer-events: none;
  background-color: rgb(30 184 245 / 70%);
  border-radius: 50%;
  transform: scale(0);
  animation: ripple 600ms linear;
}

@keyframes ripple {
  to {
    opacity: 0;
    transform: scale(4);
  }
}
接着就开始开发自定义指令了,我们要注意一件事,在插入圆dom之前,要删除圆dom,这样才能确保只有一个圆dom
import './ripple.less';
import type { Directive } from 'vue';
export const RIPPLE_NAME = 'ripple';

const createRipple = (el: HTMLElement, e: MouseEvent) => {
  // 设置按钮overflow
  el.style.overflow = 'hidden';
  // 获取按钮的长宽
  const { clientWidth, clientHeight } = el;
  // 算出直径
  const diameter = Math.ceil(Math.sqrt(clientWidth ** 2 + clientHeight ** 2));
  // 算出半径
  const radius = diameter / 2;
  // 获取按钮的全局坐标
  const { left, top } = el.getBoundingClientRect();
  // 设置按钮的定位是relative
  const position = el.style.position;
  if (!position || position === 'static') {
    el.style.position = 'relative';
  }
  // 获取鼠标点击全局坐标
  const { clientX, clientY } = e;

  // 创建一个圆dom
  const rippleEle = document.createElement('div');
  // 设置唯一标识id
  rippleEle.id = RIPPLE_NAME;
  // 设置长宽
  rippleEle.style.width = rippleEle.style.height = `${diameter}px`;
  rippleEle.style.left = `${clientX - radius - left}px`;
  rippleEle.style.top = `${clientY - radius - top}px`;
  // 插入圆dom
  el.appendChild(rippleEle);
};

const removeRipple = (el: HTMLElement) => {
  // 删除圆dom
  const rippleEle = el.querySelector(`#${RIPPLE_NAME}`);
  if (rippleEle) {
    el.removeChild(rippleEle);
  }
};

export const Ripple: Directive = {
  mounted(el: HTMLElement) {
    // 绑定点击事件
    el.addEventListener('click', e => {
      removeRipple(el);
      createRipple(el, e);
    });
  },
  unmounted(el: HTMLElement) {
    // 组件卸载时记得删了
    removeRipple(el);
  },
};

总结

以上就是点击产生水波纹效果的全部代码,是不是超级简单?快去自己试一下吧!

用户评论