vue 实现微信浮标效果
微信的浮窗,大伙应该都用过,当我们正在阅读一篇公众号文章时,突然需要处理微信消息,点击浮窗,在微信上会有个浮标,点击浮标可以再次回到文章。
我们今天打算撸一个类似微信的浮标组件,我们期望组件有以下功能
- 支持拖拽
- 支持左右吸附
- 支持页面上下滑动时隐藏
效果预览
拖拽事件
浮标的核心功能的就是拖拽,对鼠标或移动端的触摸的事件来说,有三个阶段,鼠标或手指接触到元素时,鼠标或手指在移动的过程,鼠标或手指离开元素。这个三个阶段对应的事件名称如下:
mouse: { start: 'mousedown', move: 'mousemove', stop: 'mouseup' }, touch: { start: 'touchstart', move: 'touchmove', stop: 'touchend' }
元素定位
滑动容器我们采用绝对定位,通过设置 top 和 left 属性来改变元素的位置,那我们怎么获取到新的 top 和 left 呢?
我们先看下面这张图
黄色区域是拖拽的元素,蓝色的点就是鼠标或手指触摸的位置,在元素移动的过程中,这些值也会随着发生改变,那么我们只要计算出新的触摸位置和最初触摸位置的横坐标和竖坐标的变化,就可以算出移动后的 top left ,因为拖拽的元素不随着页面滚动而变化,所以我们采用 pagex pagey 这两个值。用公式简单描述就是;
newtop = inittop + (currentpagey - initpagey) newleft = initleft + (currentpagex - initpagex)
拖拽区域
拖拽区域默认是在拖拽元素的父级元素内,所以我们需要计算出父级元素的宽高。这里有一点需要注意,如果父级的宽高是由异步事件来改变的,那么获取的时候就会不准确,这种情况就需要改变下布局。
private getparentsize() { const style = window.getcomputedstyle( this.$el.parentnode as element, null ); return [ parseint(style.getpropertyvalue('width'), 10), parseint(style.getpropertyvalue('height'), 10) ]; }
拖拽的前中后
有了上面的基础,我们分析下拖拽的三个阶段我们需要做哪些工作
- 触摸元素,即开始拖拽,将当前元素的 top left 和触摸点的 pagex pagey 用对象存储起来,然后监听移动和结束事件
- 元素拖拽过程,计算当前的 pagex pagey 与 初始的 pagex pagey 的差值,算出当前的 top left ,更新元素的位置
- 拖拽结束,重置初始值
左右吸附
在手指离开后,若元素偏向某一侧,便吸附在该侧的边上,那么在拖拽事件结束后,根据元素的x轴中心的与父级元素的x轴中心点做比较,就可知道往左还是往右移动
页面上下滑动时隐藏
使用 watch 监听父级容器的滑动事件,获取 scrolltop ,当 scrolltop 的值不在发生变化的时候,就说明页面滑动结束了,在变化前和结束时设置 left 即可。
若无法监听父级容器滑动事件,那么可以将监听事件放到外层组件,将 scrolltop 传入拖拽组件也是可以的。
代码实现
组件用的是 ts 写的,代码略长,大伙可以先收藏在看
// draggable.vue <template> <div class="dra " :class="{'dra-tran':showtran}" :style="style" @mousedown="elementtouchdown" @touchstart="elementtouchdown"> <slot></slot> </div> </template> <script lang="ts"> import { component, prop, vue, watch } from 'vue-property-decorator'; import dom from './dom'; const events = { mouse: { start: 'mousedown', move: 'mousemove', stop: 'mouseup' }, touch: { start: 'touchstart', move: 'touchmove', stop: 'touchend' } }; const userselectnone = { userselect: 'none', mozuserselect: 'none', webkituserselect: 'none', msuserselect: 'none' }; const userselectauto = { userselect: 'auto', mozuserselect: 'auto', webkituserselect: 'auto', msuserselect: 'auto' }; @component({ name: 'draggable', }) export default class draggable extends vue { @prop(number) private width !: number; // 宽 @prop(number) private height !: number; // 高 @prop({ type: number, default: 0 }) private x!: number; //初始x @prop({ type: number, default: 0 }) private y!: number; //初始y @prop({ type: number, default: 0 }) private scrolltop!: number; // 初始 scrolltop @prop({ type: boolean,default:true}) private draggable !:boolean; // 是否开启拖拽 @prop({ type: boolean,default:true}) private adsorb !:boolean; // 是否开启吸附左右两侧 @prop({ type: boolean,default:true}) private scrollhide !:boolean; // 是否开启滑动隐藏 private rawwidth: number = 0; private rawheight: number = 0; private rawleft: number = 0; private rawtop: number = 0; private top: number = 0; // 元素的 top private left: number = 0; // 元素的 left private parentwidth: number = 0; // 父级元素宽 private parentheight: number = 0; // 父级元素高 private eventsfor = events.mouse; // 监听事件 private mouseclickposition = { // 鼠标点击的当前位置 mousex: 0, mousey: 0, left: 0, top: 0, }; private bounds = { minleft: 0, maxleft: 0, mintop: 0, maxtop: 0, }; private dragging: boolean = false; private showtran: boolean = false; private prescrolltop: number = 0; private parentscrolltop: number = 0; private mounted() { this.rawwidth = this.width; this.rawheight = this.height; this.rawleft = this.x; this.rawtop = this.y; this.left = this.x; this.top = this.y; [this.parentwidth, this.parentheight] = this.getparentsize(); // 对边界计算 this.bounds = this.calcdraglimits(); if(this.adsorb){ dom.addevent(this.$el.parentnode,'scroll',this.listscorll) } } private listscorll(e:any){ this.parentscrolltop = e.target.scrolltop } private beforedestroy(){ dom.removeevent(document.documentelement, 'touchstart', this.elementtouchdown); dom.removeevent(document.documentelement, 'mousedown', this.elementtouchdown); dom.removeevent(document.documentelement, 'touchmove', this.move); dom.removeevent(document.documentelement, 'mousemove', this.move); dom.removeevent(document.documentelement, 'mouseup', this.handleup); dom.removeevent(document.documentelement, 'touchend', this.handleup); } private getparentsize() { const style = window.getcomputedstyle( this.$el.parentnode as element, null ); return [ parseint(style.getpropertyvalue('width'), 10), parseint(style.getpropertyvalue('height'), 10) ]; } /** * 滑动区域计算 */ private calcdraglimits() { return { minleft: 0, maxleft: math.floor(this.parentwidth - this.width), mintop: 0, maxtop: math.floor(this.parentheight - this.height), }; } /** * 监听滑动开始 */ private elementtouchdown(e: touchevent) { if(this.draggable){ this.eventsfor = events.touch; this.elementdown(e); } } private elementdown(e: touchevent | mouseevent) { const target = e.target || e.srcelement; this.dragging = true; this.mouseclickposition.left = this.left; this.mouseclickposition.top = this.top; this.mouseclickposition.mousex = (e as touchevent).touches ? (e as touchevent).touches[0].pagex : (e as mouseevent).pagex; this.mouseclickposition.mousey = (e as touchevent).touches ? (e as touchevent).touches[0].pagey : (e as mouseevent).pagey; // 监听移动事件 结束事件 dom.addevent(document.documentelement, this.eventsfor.move, this.move); dom.addevent( document.documentelement, this.eventsfor.stop, this.handleup ); } /** * 监听拖拽过程 */ private move(e: touchevent | mouseevent) { if(this.dragging){ this.elementmove(e); } } private elementmove(e: touchevent | mouseevent) { const mouseclickposition = this.mouseclickposition; const tmpdeltax = mouseclickposition.mousex - ((e as touchevent).touches ? (e as touchevent).touches[0].pagex : (e as mouseevent).pagex) || 0; const tmpdeltay = mouseclickposition.mousey - ((e as touchevent).touches ? (e as touchevent).touches[0].pagey : (e as mouseevent).pagey) || 0; if (!tmpdeltax && !tmpdeltay) return; this.rawtop = mouseclickposition.top - tmpdeltay; this.rawleft = mouseclickposition.left - tmpdeltax; this.$emit('dragging', this.left, this.top); } /** * 监听滑动结束 */ private handleup(e: touchevent | mouseevent) { this.rawtop = this.top; this.rawleft = this.left; if (this.dragging) { this.dragging = false; this.$emit('dragstop', this.left, this.top); } // 左右吸附 if(this.adsorb){ this.showtran = true const middlewidth = this.parentwidth / 2; if((this.left + this.width/2) < middlewidth){ this.left = 0 }else{ this.left = this.bounds.maxleft - 10 } settimeout(() => { this.showtran = false }, 400); } this.resetboundsandmousestate(); } /** * 重置初始数据 */ private resetboundsandmousestate() { this.mouseclickposition = { mousex: 0, mousey: 0, left: 0, top: 0, }; } /** * 元素位置 */ private get style() { return { position: 'absolute', top: this.top + 'px', left: this.left + 'px', width: this.width + 'px', height: this.height + 'px', ...(this.dragging ? userselectnone : userselectauto) }; } @watch('rawtop') private rawtopchange(newtop: number) { const bounds = this.bounds; if (bounds.maxtop === 0) { this.top = newtop; return; } const left = this.left; const top = this.top; if (bounds.mintop !== null && newtop < bounds.mintop) { newtop = bounds.mintop; } else if (bounds.maxtop !== null && bounds.maxtop < newtop) { newtop = bounds.maxtop; } this.top = newtop; } @watch('rawleft') private rawleftchange(newleft: number) { const bounds = this.bounds; if (bounds.maxtop === 0) { this.left = newleft; return; } const left = this.left; const top = this.top; if (bounds.minleft !== null && newleft < bounds.minleft) { newleft = bounds.minleft; } else if (bounds.maxleft !== null && bounds.maxleft < newleft) { newleft = bounds.maxleft; } this.left = newleft; } @watch('scrolltop') // 监听 props.scrolltop @watch('parentscrolltop') // 监听父级组件 private scorlltopchange(newtop:number){ let timer = undefined; if(this.scrollhide){ cleartimeout(timer); this.showtran = true; this.prescrolltop = newtop; this.left = this.bounds.maxleft + this.width - 10 timer = settimeout(()=>{ if(this.prescrolltop === newtop ){ this.left = this.bounds.maxleft - 10; settimeout(()=>{ this.showtran = false; },300) } },200) } } } </script> <style lang="css" scoped> .dra { touch-action: none; } .dra-tran { transition: top .2s ease-out , left .2s ease-out; } </style>
// dom.ts export default { addevent(el: any, event: string, handler: any) { if (!el) { return; } if (el.attachevent) { el.attachevent('on' + event, handler); } else if (el.addeventlistener) { el.addeventlistener(event, handler, true); } else { el['on' + event] = handler; } }, removeevent(el: any, event: string, handler: any) { if (!el) { return; } if (el.detachevent) { el.detachevent('on' + event, handler); } else if (el.removeeventlistener) { el.removeeventlistener(event, handler, true); } else { el['on' + event] = null; } } };
总结
以上所述是小编给大家介绍的vue 实现微信浮标效果,希望对大家有所帮助