Vue div拖拽限制移动范围

文章介绍了一种在Vue中使用自定义指令(v-drag)实现元素拖拽并限制其移动范围在容器内的方法。通过计算元素和父容器的位置,阻止元素超出容器边界。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值