需求:多入口需懸掛在頁面中,用戶可以隨意拖動,方便在頁面上的多操作,如下圖
思路:按鈕拖動分爲三步驟,拖動開始(ontouchstart)、拖動中(ontouchmove)、拖動結束(ontouchend)
在拖動開始,獲取當前橫縱座標點位置,判斷當前位置點距離屏幕左右位置獲取相對屏幕的相對定位left、top,動態改變實現按鈕拖動效果
1、按鈕元素綁定ontouchstart、ontouchmove、ontouchend三個事件,相對定位left、top
<image src="XX" style="left: {{menuStyle.left+'px'}}; top:{{menuStyle.top+'px'}}" ontouchstart="menuTouchStart" ontouchmove="menuTouchMove" ontouchend="menuTouchEnd" ></image>
export default{
return(){
menuStyle:{
left: 880, //菜單絕定定位頂部位置
top: 1030, //菜單絕定定位左側位置
disX: 0,
disY: 0
},
beginDrag: false
}
}
2、事件
(1)ontouchstart 拖動開始事件,獲取距離事件觸發對象左邊沿 X 、Y軸的距離
menuTouchStart(event){
this.beginDrag = true;
this.menuStyle.disX = event.touches[0].offsetX;
this.menuStyle.disY = event.touches[0].offsetY;
}
(2) ontouchmove 拖動中事件,在獲取到座標點按鈕會跑出屏幕外,需要加判斷,判斷按鈕左高距離屏幕位置,爲了兼容安卓有的手機屏幕可視高度、寬度,當觸摸座標大於屏幕的可使用窗口寬、高時,屏幕可視寬高爲可使用窗口/設備的屏幕密度。通過可見區域左邊沿的 X、Y 軸座標減去距離事件觸發對象左邊沿 X 、Y軸的距離得到按鈕相對屏幕左、高位移。
menuTouchMove(event){
if(this.beginDrag){
event.stopPropagation()
let resetDeviceScreenWidth = event.touches[0].clientX > this.device.windowWidth ? ((this.device.windowWidth / this.device.screenDensity) * 3) : this.device.windowWidth;
let resetDeviceScreenHeight = event.touches[0].clientY > this.device.windowHeight ? ((this.device.windowHeight / this.device.screenDensity) * 3) : this.device.windowHeight;
let menuStyleLeft = event.touches[0].clientX - this.menuStyle.disX;
let menuStyleTop = event.touches[0].clientY - this.menuStyle.disY;
this.menuStyle.left = menuStyleLeft > 0 ?(menuStyleLeft > (resetDeviceScreenWidth - 204) ? resetDeviceScreenWidth - 204 : menuStyleLeft) : 0 ;
this.menuStyle.top = menuStyleTop > 0 ?(menuStyleTop > (resetDeviceScreenHeight - 204) ? resetDeviceScreenHeight - 204 : menuStyleTop) : 0 ;
}
}
(3)ontouchend 拖動結束事件,重置數據
menuTouchEnd(){
this.beginDrag = false;
this.menuStyle.disX = this.menuStyle.disY = 0;
}