vue的拖拽移动不超出屏幕可视宽度
时间: 2023-08-13 15:09:11 浏览: 122
要实现Vue的拖拽移动不超出屏幕可视宽度,可以在上面提到的基础上进行如下修改:
1. 在mounted钩子函数中,获取父级容器的可视宽度
2. 在mousemove事件中,计算出拖拽元素应该移动的位置时,要将父级容器的可视宽度考虑在内,并且要注意不要超出屏幕可视宽度
3. 在mouseup事件中,要将拖拽元素的left值再次进行限制,以防止出现拖拽元素只有部分可见的情况
下面是一个修改后的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,
parentWidth: 0
}
},
mounted() {
this.maxWidth = this.$el.parentNode.clientWidth - this.$el.clientWidth
this.maxHeight = this.$el.parentNode.clientHeight - this.$el.clientHeight
this.parentWidth = this.$el.parentNode.clientWidth
},
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)
if (this.left + this.$el.clientWidth > this.parentWidth) {
this.left = this.parentWidth - this.$el.clientWidth
}
}
},
handleMouseUp(e) {
this.isDragging = false
this.left = Math.min(Math.max(this.left, 0), this.maxWidth)
document.removeEventListener('mousemove', this.handleMouseMove)
document.removeEventListener('mouseup', this.handleMouseUp)
}
}
}
</script>
<style>
.drag {
position: absolute;
cursor: move;
}
</style>
```
在父级容器上使用该组件,即可实现拖拽移动不超出屏幕可视宽度。
阅读全文