<template>
<div ref="element" class="content" v-drag draggable="false">
<p>文字网页</p>
</div>
</template>
<script >
export default {
data() {
return {
};
},
directives: {
drag(el) {
let oDiv = el; //当前元素
// 按下元素事件绑定元素被按下时发生
oDiv.ontouchstart = function (e) {
let disX = e.targetTouches[0].clientX - oDiv.offsetLeft;
let disY = e.targetTouches[0].clientY - oDiv.offsetTop;
// 按下后移动元素事件,能获取元素的位置
document.ontouchmove = function (e) {
// 通过事件委托,计算移动的距离
let l = e.changedTouches[0].clientX - disX;
let t = e.changedTouches[0].clientY - disY;
// 控制左边拖拽的距离
if (l < 0) {
l = 0;
}
// 控制上边拖拽的距离
if (t < 0) {
t = 0;
}
// 控制下边拖拽的距离
if (t > window.screen.height - 100) {
//用可视窗口减去div的高度
t = window.screen.height - 100;
}
// 控制右边拖拽的距离
if (l > window.screen.width - 100) {
//用可视窗口减去div的宽度
l = window.screen.width - 100;
}
//移动当前元素
oDiv.style.left = l + "px";
oDiv.style.top = t + "px";
};
};
},
},
};
</script>
<style>
.content {
position: absolute;
height: 100px;
width: 100px;
background-color: #67c23a;
}
</style>
vue2中v-drag如何实现拖拽(移动端)
猜你喜欢
转载自blog.csdn.net/zhaojiaxing123/article/details/129493780
今日推荐
周排行