快应用之--模仿苹果手机屏幕的虚拟键,可以在手机上随意拖动

需求:多入口需悬挂在页面中,用户可以随意拖动,方便在页面上的多操作,如下图

 

快应用之--模仿苹果手机屏幕的虚拟键,可以在手机上随意拖动_第1张图片

思路:按钮拖动分为三步骤,拖动开始(ontouchstart)、拖动中(ontouchmove)、拖动结束(ontouchend)

在拖动开始,获取当前横纵坐标点位置,判断当前位置点距离屏幕左右位置获取相对屏幕的相对定位left、top,动态改变实现按钮拖动效果

1、按钮元素绑定ontouchstart、ontouchmove、ontouchend三个事件,相对定位left、top




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;

 }

 

你可能感兴趣的:(快应用,js,html)