实现一张图片跟随鼠标移动,同时在限定移动范围

dom层:

<div class="poster" ref="posterRef">
        <img
          :src="uploadImg.link"
          alt=""
          class="bg-img"
          draggable="false"
          v-if="uploadImg.link"
        />
        <img
          src="@/assets/img/text-code.jpg"
          alt=""
          ref="codeRef"
          :style="{
            left: leftX + 'px',
            top: topY + 'px',
            width: qrcodeWidth + 'px',
            height: qrcodeWidth + 'px',
          }"
          class="code-img"
          @mousedown.prevent="handleMouseDown"
          v-if="uploadImg.link"
        />
      </div>

样式:

.poster {
  position: relative;
  width: 528px;
  height: 834px;
  background-color: #d9d9d9;
  .bg-img {
    width: 100%;
    height: 100%;
  }
  .code-img {
    position: absolute;
    width: 212px;
    height: 212px;
    border-radius: 50%;
  }
}

js:

handleMouseDown(event) {
      // 1,计算位置差
      // 因为clientX和offsetLeft的属性返回的位置不一样 要相减得到鼠标在拖动元素内实际点击的位置
      // 后面每一次拖动时都要减去这个差值 否则就会造成你拖动的位置一直都是元素的左上角 而不是你之前点击的位置
      this.disX = event.clientX - this.codeimg.offsetLeft
      this.disY = event.clientY - this.codeimg.offsetTop

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

      // 添加鼠标移动事件
      document.onmousemove = (el) => {
        // 3,获取鼠标移动位置
        let moveX = el.clientX - this.disX
        let moveY = el.clientY - this.disY

        // 4,限制拖动
        //控制范围:在元素 被拖拽的过程中 判断 元素的定位值 是否到达边界 如果到了 就不能在走了
        // 左边界
        if (moveX <= 0) {
          moveX = 0
        }
        // 上边界
        if (moveY <= 0) {
          moveY = 0
        }
        // 下边界  容器高度 - 拖动元素高度
        if (moveY >= dragContainerHeight - dragHeight) {
          moveY = dragContainerHeight - dragHeight
        }

        //右边界   容器宽度 - 拖动元素宽度
        if (moveX >= dragContainerWidth - dragWidth) {
          moveX = dragContainerWidth - dragWidth
        }

        // 5, 开始移动
        this.leftX = moveX
        this.topY = moveY
      }
      /* 6,鼠标抬起解除事件 */
      document.onmouseup = () => {
        document.onmousemove = null
      }
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容