• Vue中实现div的任意移动


    前言

    在系统应用中,像图片,流程预览及打印预览等情况,当前视窗无法全部显示要预览的全部内容,设置左右和上下滚动条后,如果用鼠标拖动滚动条,又不太便利,如何用鼠标随意的移动呢?

    核心方法及事件

    可以借助mousedownmouseupmousemove三个事件来处理内容的移动与起始、结束的控制,再借助getComputedStyle动态设置移动内容的left,top,以实现区域的随意移动。

    简单代码示例

    <template>
      <div>
        <div style="display: flex; justify-content: center">
          <div class="main">
            
          </div>
        </div>
      </div>
    </template>
    <script lang="ts" setup>
    import { ref, reactive, onMounted } from 'vue'
    onMounted(() => {
      moveNode()
    })
    function moveNode() {
      const child = document.querySelector('.main')
      let isDragging = false
      let prevX = 0
      let prevY = 0
      child.addEventListener('mousedown', function (e) {
        isDragging = true
        prevX = e.clientX
        prevY = e.clientY
      })
      child.addEventListener('mouseup', function () {
        isDragging = false
      })
      child.addEventListener('mousemove', function (e) {
        if (isDragging) {
          const diffX = e.clientX - prevX
          const left = parseInt(window.getComputedStyle(child).left) || 0
          child.style.left = `${left + diffX}px`
          prevX = e.clientX
          const diffY = e.clientY - prevY
          const top = parseInt(window.getComputedStyle(child).top) || 0
          child.style.top = `${top + diffY}px`
          prevY = e.clientY
        }
      })
    }
    </script>
    <style lang="less" scoped>
    .main {
      position: relative;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      height: 500px;
      width: 500px;
      background-color: red;
      cursor: move;
    }
    </style>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    动态演示

    在这里插入图片描述

  • 相关阅读:
    Go 语言基础语法 3
    TPM零知识学习二—— 相关链接和页面
    Effective C++改善程序与设计的55个具体做法 3. 资源管理
    CSDN客诉周报第3期|本周解决22个问题,实现2个用户需求
    ESP8266使用记录(一)
    全连接网络参数Xavier初始化
    Jackson指定json的key
    Spring Cloud框架(原生Hoxton版本与Spring Cloud Alibaba)初级篇 ---- 服务注册与发现
    Java开发的模板引擎--freemarker
    @Spring面试题
  • 原文地址:https://blog.csdn.net/lqh4188/article/details/134493998