vue页面实现div的拖动

<template>

  <div id="Drag" @mousedown="mousedown($event)" class="drag"></div>

</template>

<script>
  export default {
    name: "Drag",
    data() {
      return {
        DragEl: null, //拖动元素
        totalHeight: null,
        totalWidth: null,
        // 位置差
        disX: 0,
        disY: 0,
      };
    },
    mounted() {
      this.DragEl = document.getElementById("Drag");
      this.totalHeight = window.innerHeight;
      this.totalWidth = window.innerWidth;
      console.log(this.totalHeight, this.totalWidth)
    },
    methods: {
      /* 鼠标按下 */
      mousedown(event) {
        // 1,计算位置差
        // 因为clientX和offsetLeft的属性返回的位置不一样 要相减得到鼠标在拖动元素内实际点击的位置
        // 后面每一次拖动时都要减去这个差值 否则就会造成你拖动的位置一直都是元素的左上角 而不是你之前点击的位置
        this.disX = event.clientX - this.DragEl.offsetLeft;
        this.disY = event.clientY - this.DragEl.offsetTop;

        //2, 获取拖动元素的高度和容器的高度 为了下面进行限制元素拖动的范围
        let dragHeight = this.DragEl.offsetHeight;
        let dragWidth = this.DragEl.offsetWidth;

        // 添加鼠标移动事件
        document.onmousemove = (el) => {
          // 3,获取鼠标移动位置
          let moveX = el.clientX - this.disX;
          let moveY = el.clientY - this.disY;
          console.log(moveX, moveY)
          // 4,限制拖动
          //控制范围:在元素 被拖拽的过程中 判断 元素的定位值 是否到达边界 如果到了 就不能在走了

          //4.1第一种 限制范围的判断
          // if(moveX <=0 || moveY <=0){ // 控制上边界和左边界
          //   return
          // }
          // if(moveX >= dragContainerWidth - dragWidth || moveY >= dragContainerHeight - dragHeight){
          //   return
          // }

          // 4.2 第二种限制方位的判断 建议使用第二种; 第一种靠边时经常会有边距,不太丝滑
          // 左边界
          if (moveX <= 210) {
            moveX = 210;
          }
          // 右边界 减去的值为div的宽度
          if (moveX >= this.totalWidth-50 ) {
            moveX = this.totalWidth-50  ;
          }
          // 上边界
          if (moveY <= 50) {
            moveY = 50;
          }
          // 上边界减去的值为div的高度
          if (moveY >= this.totalHeight-50) {
            moveY = this.totalHeight-50;
          }
          // 5, 开始移动
          this.DragEl.style.left = moveX + "px";
          this.DragEl.style.top = moveY + "px";
        };
        /* 6,鼠标抬起解除事件 */
        document.onmouseup = () => {
          document.onmousemove = null;
        };
      }
    }
  };
</script>
<style scoped lang="scss">
  .drag {
    position: fixed;
    width: 50px;
    height: 50px;
    border: 5px solid yellowgreen;
    background-color: red;
    text-align: center;
    left: 50%;
    top: 50%;
  }
</style>

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值