Vue 组件拖拽限制移动范围
需求:将元素的可拖拽范围限制在容器内
完成思路: 基于vue v-drag 拖动 拖拽 移动div 拖拽滑动div修改,加上了移动范围限制。
直接上代码:
<script>
import {ref,reactive,computed,watch} from 'vue'
export default {
name: "home",
//测试setup,暂时不考虑响应式
setup(){
},
directives: {
drag(el){
let oDiv = el; //当前元素
let pDiv = el.parentNode; //父元素
let self = this; //上下文
let rangWidth = pDiv.clientWidth; //父元素宽度,即 移动范围
let rangHeight = pDiv.clientHeight; //父元素高度
//禁止选择网页上的文字
document.onselectstart = function() {
return false;
};
oDiv.onmousedown = function(e){
//鼠标按下,计算当前元素距离可视区的距离
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
const dWdith = oDiv.clientWidth;
const dHeight = oDiv.clientHeight;
const dMoveLeft = rangWidth - dWdith;
const dMoveTop = rangHeight - dHeight;
document.onmousemove = function(e){
//通过事件委托,计算移动的距离
let left = e.clientX - disX;
let top = e.clientY - disY;
//移动当前元素
// oDiv.style.left = l + "px";
// oDiv.style.top = t + "px";
//如果元素的移动位置大于窗口位置,则不再移动
if(left > dMoveLeft){
oDiv.style.left = `${dMoveLeft}px`;
}else{
oDiv.style.left = `${left}px`;
}
if(left <0){
oDiv.style.left = `0px`;
}
if(top > dMoveTop){
oDiv.style.top = `${dMoveTop}px`;
}else{
oDiv.style.top = `${top}px`;
}
if(top < 0){
oDiv.style.top = `0px`;
}
}
document.onmouseup = function(e){
document.onmousemove = null;
document.onmouseup = null;
};
//return false不加的话可能导致黏连,就是拖到一个地方时div粘在鼠标上不下来,相当于onmouseup失效
return false;
};
}
},
}
</script>
<template>
<div class="container">
<div class="box" v-drag></div>
</div>
</template>
<style scoped lang="less">
body{
padding: 0;
margin: 0;
border: 0;
}
.container{
position: relative;
width: 800px;
height: 500px;
background-color: aqua;
.box{
position: absolute;
width: 100px;
height: 100px;
background-color: burlywood;
}
}
</style>