這兩天在作一個項目,有個小模塊是懸浮球功能,能夠拖動的那種this
組件也找了,發現組件那個會很卡,並且頁面會跟着滾動,球球初始位置也讓人很難受spa
尤爲是當我一刷新球球丟了就很蒙,看來那個仍是須要完善的code
而後我去百度搜了搜,而後找到了解決方法,我判斷了下球球初始狀況blog
初始是按百分比定位的,這樣對一些大屏設備仍是比較友好的,事件
並且我還精簡了下代碼圖片
完整的可拖動懸浮球功能以下(可複製直接使用):ip
注:若是球球是圖片的話,只須要把ball的那個view改爲image便可get
<template> <view> <view class="holdon"> <view class="ball" :style="'left:'+(moveX == 0 & x>0? x+'%':moveX+'px')+';top:'+(moveY == 0 & y>0? y+'%':moveY+'px')" @touchstart="drag_start" @touchmove.prevent="drag_hmove" mode="aspectFit"> </view> </view> </view> </template> <script> export default { //懸浮球絕對位置百分比,頁面刷新會回到這個位置 props: { x: { type: Number, default: 80 }, y: { type: Number, default: 50 }, image: { type: String, default: '' } }, data() { return { start: [0, 0], moveY: 0, moveX: 0, windowWidth: '', windowHeight: '', } }, onShow() { //獲取系統分辨率 const { windowWidth, windowHeight } = uni.getSystemInfoSync(); this.windowWidth = windowWidth this.windowHeight = windowHeight }, methods: { drag_start(event) { this.start[0] = event.touches[0].clientX - event.target.offsetLeft; this.start[1] = event.touches[0].clientY - event.target.offsetTop; }, //判斷防止懸浮球被拖出頁面 drag_hmove(event) { let tag = event.touches; if (tag[0].clientX < 0) { tag[0].clientX = 0 } if (tag[0].clientY < 0) { tag[0].clientY = 0 } if (tag[0].clientX > this.windowWidth) { tag[0].clientX = this.windowWidth } if (tag[0].clientY > this.windowHeight) { tag[0].clientY = this.windowHeight } this.moveX = tag[0].clientX - this.start[0]; this.moveY = tag[0].clientY - this.start[1]; }, } } </script> <style> .ball { width: 100rpx; height: 100rpx; background: linear-gradient(to bottom, #F8F8FF, #87CEFA); border-radius: 50%; /* 防止頁面滾動條或其餘事件跟着動 */ position: fixed !important; z-index: 9999; } </style>