<div id="parent" style="width: 100%;height: 100%;position: relative">
<div
@touchmove.prevent="touchmove"
@touchend.prevent="touchend"
@touchstart.prevent="touchstart"
@click="sample" id="child"
class="draggable-item" >
</div>
</div>
拖拽部分的样式为,因为一进来的时候需要定位在一个地方,然后在随意拖拽不超出当前当前页面
.draggable-item{
width: 168px;
height: 137px;
background-image: url("../../assets/img/menu/hang.png");
background-size: 100% 100%;
position: absolute;
right: 27px;
top: 356px;
z-index: 99999;
}
然后就是触摸的时候的代码了
touchend(){
let self = this;
clearTimeout(self.Loop);
if (self.Loop !== 0) {
alert('点击事件')
this.sample()
}
return false;
},
touchstart(event){
let child = document.getElementById('child')
this.startX = event.targetTouches[0].pageX - child.offsetLeft;
this.startY = event.targetTouches[0].pageY - child.offsetTop;
let self = this;
//执行长按的内容
self.Loop = setTimeout(function () {
self.Loop = 0;
}, 200);
return false;
},
touchmove(event){
let child = document.getElementById('child')
event.preventDefault()
event.stopPropagation()
this.leftX = event.targetTouches[0].pageX - this.startX;
this.topY = event.targetTouches[0].pageY - this.startY;
this.maxX = this.maxW - parseInt(window.getComputedStyle(child).width)-5
this.maxY = this.maxH - parseInt(window.getComputedStyle(child).height)-5
if (this.leftX < 0) {
this.leftX = 0
} else if (this.leftX > this.maxX) {
this.leftX = this.maxX
}
if (this.topY < 0) {
this.topY = 0
} else if (this.topY > this.maxY) {
this.topY = this.maxY
}
child.style.left = this.leftX + "px";
child.style.top = this.topY + "px";
},
如果遇到触摸事件和点击事件发生冲突,请看另一篇文章vue h5页面 解决touchstart,touchmove,touchend,click事件触发产生的问题_茂菇凉的博客-CSDN博客