教你使用vue写一个拖拽功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
效果图
实现步骤html
总结了一下评论,好像发现大家都碰到了滑动的问题。就在这里提醒一下吧。可将该悬浮 DIV 同你的 scroller web 同级。
<template>
<div id="webId">
<div>你的web页面</div>
<!-- 1.1 如果碰到滑动问题,请检查这里是否属于同一点。 -->
<!-- 悬浮的HTML -->
<div class="xuanfu" id="moveDiv"
@mousedown="down()" @touchstart="down()"
@mousemove.prevent.stop="move()"
@touchmove.prevent.stop="move()"
@mouseup="end()" @touchend="end()"
>
<div class="yuanqiu">11</div>
</div>
</div>
</template>
js
<script>
data() {
return {
flags: false,
position: { x: 0, y: 0 },
nx: '', ny: '', dx: '', dy: '', xPum: '', yPum: '',
}
}
methods: {
// 实现移动端拖拽
down(){
this.flags = true;
let touch;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
this.position.x = touch.clientX;
this.position.y = touch.clientY;
this.dx = moveDiv.offsetLeft;
this.dy = moveDiv.offsetTop;
},
move(){
if(this.flags){
let touch ;
if(event.touches){
touch = event.touches[0];
}else {
touch = event;
}
this.nx = touch.clientX - this.position.x;
this.ny = touch.clientY - this.position.y;
this.xPum = this.dx+this.nx;
this.yPum = this.dy+this.ny;
//添加限制:只允许在屏幕内拖动
const maxWidth = document.body.clientWidth - 54;//屏幕宽度减去悬浮框宽高
const maxHeight = document.body.clientHeight - 54;
if (this.xPum < 0) { //屏幕x限制
this.xPum = 0;
} else if (this.xPum>maxWidth) {
this.xPum = maxWidth;
}
if (this.yPum < 0) { //屏幕y限制
this.yPum = 0;
} else if (this.yPum>maxHeight) {
this.yPum = maxHeight;
}
moveDiv.style.left = this.xPum+"px";
moveDiv.style.top = this.yPum +"px";
//阻止页面的滑动默认事件
document.addEventListener("touchmove",function(){ // 1.2 如果碰到滑动问题,请注意是否获取到 touchmove
event.preventDefault();//jq 阻止冒泡事件
// event.stopPropagation(); // 如果没有引入jq 就用 stopPropagation()
},false);
}
},
//鼠标释放时候的函数
end(){
this.flags = false;
},
}
</script>
css
<style>
/*css样式可自定义 仅提供参考*/
#webId { position: relative; }
.xuanfu {
height: 54px; /* rem = 12px */
width: 54px;
/*1.3 如果碰到滑动问题,请检查 z-index。z-index需比web大一级*/
z-index: 999;
position: fixed;
top: 4.2rem;
right: 3.2rem;
border-radius: 0.8rem;
background-color: rgba(0, 0, 0, 0.55);
}
.yuanqiu {
height: 2.7rem;
width: 2.7rem;
border: 0.3rem solid rgba(140, 136, 136, 0.5);
margin: 0.65rem auto;
color: #000000;
font-size: 1.6rem;
line-height: 2.7rem;
text-align: center;
border-radius: 100%;
background-color: #ffffff;
}
</style>
看完上述内容,你们掌握教你使用vue写一个拖拽功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。