Vue中实现div的任意移动
前言
在系统应用中,像图片,流程预览及打印预览等情况,当前视窗无法全部显示要预览的全部内容,设置左右和上下滚动条后,如果用鼠标拖动滚动条,又不太便利,如何用鼠标随意的移动呢?
核心方法及事件
可以借助mousedown
,mouseup
,mousemove
三个事件来处理内容的移动与起始、结束的控制,再借助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>