须要在页面上加上一个悬浮图标,大体是以下图的最终实现vue
可是每每按照设计稿是不会遮住主体区域的,可是实际上有时候恰恰会遮挡主体区域,可是为了更好的点击量,又不得不悬浮在页面上...jquery
若是能让图标可拖拽移动,这样在遮住主体区域以后,用户可自由移动,这种方案及能够兼顾了。bash
实现的效果以下:
(和微信的浮窗效果相似,左右位置靠边显示,上下位置随意放)微信
话很少说,上代码了app
<div class="ys-float-btn"
:style="{'width': itemWidth+'px','height': itemHeight+'px','left': left+'px','top': top+'px'}"
ref="div"
@touchstart.prevent="(e) => {dragStart(e)}"
@touchend.prevent="(e) => {dragEnd(e)}"
@touchmove.prevent="(e) => {dragProgress(e)}"
>
<img src="./../assets/fc-icon.png" />
</div>复制代码
// 代码直接在 vue 项目里,可自行改成js/jquery 写法
data () {
return {
gapWidth: 10,
itemWidth: 20, // 图标的宽度
itemHeight: 30 // 图标的高度
}
},
created() {
this.clientWidth = document.documentElement.clientWidth;
this.clientHeight = document.documentElement.clientHeight;
this.left = this.clientWidth - this.itemWidth - this.gapWidth;
this.top = this.clientHeight*0.8; }
methods: {
dragStart(e) {
this.$refs.div.style.transition = 'none';
},
dragEnd(e) {
this.$refs.div.style.transition = 'all 0.3s';
if (this.left > this.clientWidth/2) {
this.left = this.clientWidth - this.itemWidth - this.gapWidth;
} else {
this.left = this.gapWidth;
}
},
dragProgress(e) {
if (e.targetTouches.length === 1) {
let touch = event.targetTouches[0];
this.left = touch.clientX - this.itemWidth/2;
this.top = touch.clientY - this.itemHeight/2;
}
}
}复制代码
以上代码既能够上下也能够左右移动,若是只想让可上下移动,就去掉 left 相关的设置和计算。ui