vue的拖拽移动不超出屏幕外
时间: 2023-08-13 14:09:11 浏览: 285
vue实现拖拽的简单案例 不超出可视区域
要实现Vue的拖拽移动不超出屏幕外,可以通过以下步骤实现:
1. 在拖拽元素的父级容器上绑定mousedown、mousemove和mouseup事件
2. 在mousedown事件中获取鼠标的初始位置和拖拽元素的初始位置,并计算出它们的偏移量
3. 在mousemove事件中根据鼠标的位置和偏移量计算出拖拽元素应该移动的位置,但是要注意不要超出父级容器的边界
4. 在mouseup事件中解绑mousemove和mouseup事件,结束拖拽
下面是一个简单的Vue拖拽组件示例:
```
<template>
<div class="drag" @mousedown="handleMouseDown">
<slot></slot>
</div>
</template>
<script>
export default {
data() {
return {
isDragging: false,
startX: 0,
startY: 0,
offsetX: 0,
offsetY: 0,
left: 0,
top: 0,
maxWidth: 0,
maxHeight: 0
}
},
mounted() {
this.maxWidth = this.$el.parentNode.clientWidth - this.$el.clientWidth
this.maxHeight = this.$el.parentNode.clientHeight - this.$el.clientHeight
},
methods: {
handleMouseDown(e) {
e.preventDefault()
this.isDragging = true
this.startX = e.clientX
this.startY = e.clientY
this.offsetX = this.$el.offsetLeft
this.offsetY = this.$el.offsetTop
document.addEventListener('mousemove', this.handleMouseMove)
document.addEventListener('mouseup', this.handleMouseUp)
},
handleMouseMove(e) {
if (this.isDragging) {
const left = e.clientX - this.startX + this.offsetX
const top = e.clientY - this.startY + this.offsetY
this.left = Math.min(Math.max(left, 0), this.maxWidth)
this.top = Math.min(Math.max(top, 0), this.maxHeight)
}
},
handleMouseUp(e) {
this.isDragging = false
document.removeEventListener('mousemove', this.handleMouseMove)
document.removeEventListener('mouseup', this.handleMouseUp)
}
}
}
</script>
<style>
.drag {
position: absolute;
cursor: move;
}
</style>
```
在父级容器上使用该组件,即可实现拖拽移动不超出屏幕外。
阅读全文