須要在頁面上加上一個懸浮圖標,大體是以下圖的最終實現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