程序员

vue2实现material风格的组件之button

2017-03-21  本文已影响0人  BrotherWy

前言

最近学vue2的时候发现好像没有基于vue2的一个material design风格的组件库,因为自己对这种风格是特别的喜爱,第一次看到的时候甚至有惊艳的感觉,所以想着自己从零自己去整一个!!今天就先写一个Button吧!!!

搭建环境

安装好vue-cli,node等等一系列的工具后,新建项目

  vue init webpack vue-material

然后就开始写吧:
先上个效果图

Video_2017-03-21_192619.gif

这就是经典的水波纹效果,第一次看的我都惊呆了!!下面就来讲讲水波纹到底是怎么弄的吧

思路

就是点击一个按钮后,在点击的位置让在按钮内部的一个圆形,从0放大到2倍,注意按钮设置属性overflow:hidden.
关键点:
动态添加<span class="ripple"></span>
根据鼠标点击的位置,把圆心到该位置:
动画:放大效果
清除动态添加的span (这点我做的不是很好。有点小bug)

设置一个按钮

注意dom结构,按钮内部的圆形区域是后来动态的添加上去的

<button @click="ripple" ref="btn" class="vm-btn" >
        默认按钮
</button>
button
  position relative
  display: inline-block;
  white-space: nowrap;
  cursor: pointer;
  border: none
  outline: none;
  margin: 0;
  padding: 8px 25px;
  font-size: 14px;
  overflow hidden
  background: gray
  color:white

button内部的圆形

记住他不是直接加上去的,他是后来动态的加上去的,
动画就是放大了1倍

<span class="ripple"></span>
.ripple
        position: absolute;
        border-radius: 100%;
        transform: scale(0);
        pointer-events: none;
.show
        animation: ripple .75s ease-out forwards;
 @keyframes ripple
        to
            transform: scale(2);
            opacity 0

js动态的添加ripple

看上面点击事件注册的是:ripple

       methods: {
            ripple: function (e){
                this.createRipple(e);//创建dom
                this.clearRipple(e);//清除dom
            },
            createRipple: function (e) {
                //创建ripple
                const ripple = document.createElement('span');
                ripple.className = 'ripple';
                const btn = this.$refs.btn;
                //获取按钮宽高最大的作为水波纹的宽、高
                const max = Math.max(btn.clientWidth, btn.clientHeight);
                ripple.style.height = ripple.style.width = max + 'px';
                //水波纹中心位置 = 鼠标的位置 - 水波纹的宽高的一半
                ripple.style.top = e.offsetY - max / 2 + 'px';
                ripple.style.left = e.offsetX - max / 2 + 'px';
                //添加动画
                ripple.classList.add('show');
                e.target.appendChild(ripple);
            },
            clearRipple: function (e) {//清除ripple
                /**
                 * 水波纹标签清除不完全 bug  记录一下
                 */
                if (!this.timer) {
                    this.timer = setTimeout(() => {
                        e.target.childNodes.forEach(function (self) {
                            if (self.style)//只有水波纹会删除
                                e.target.removeChild(self)
                        });
                       this.timer = "";
                    }, 1000)
                }
            }
        },

完整组件代码

github地址:https://github.com/BrotherWY/vue2-material
演示地址:http://brotherwang.online:8081/#/
nginx 配置出错 快熄灯了 先这样 明天再说

上一篇 下一篇

猜你喜欢

热点阅读