vuedraggable禁止拖拽出所在区域
时间: 2023-09-18 10:14:27 浏览: 24
可以通过设置`contaiment`属性来限制拖拽的范围,这个属性可以设置为一个包含四个值的数组,分别代表左边界、上边界、右边界和下边界。例如,如果你想限制拖拽在一个名为`drag-container`的区域内,可以这样写:
```html
<template>
<div class="drag-container">
<draggable :list="items" :options="{ containment: [0, 0, 500, 500] }">
<!-- draggable items -->
</draggable>
</div>
</template>
```
这里的`contaiment`数组表示拖拽区域的左上角坐标为`(0, 0)`,右下角坐标为`(500, 500)`。
注意,`containment`属性只能限制拖拽的范围,但是不能禁止拖拽出所在区域。如果需要禁止拖拽出所在区域,可以在`dragstart`事件中记录当前元素的位置,在`drag`事件中检查是否超出了容器范围,如果超出了就将元素移回原来的位置。具体实现可以参考下面的代码:
```html
<template>
<div class="drag-container" ref="container">
<draggable :list="items" @dragstart="onDragStart" @drag="onDrag" @dragend="onDragEnd">
<!-- draggable items -->
</draggable>
</div>
</template>
<script>
export default {
data() {
return {
items: [], // your draggable items
currentItem: null, // the current item being dragged
containerBounds: null, // the bounding rect of the container
itemBounds: null, // the bounding rect of the current item
lastX: 0, // the last x position of the item
lastY: 0 // the last y position of the item
};
},
mounted() {
this.containerBounds = this.$refs.container.getBoundingClientRect();
},
methods: {
onDragStart(event) {
this.currentItem = event.item;
this.itemBounds = this.currentItem.getBoundingClientRect();
this.lastX = this.itemBounds.left;
this.lastY = this.itemBounds.top;
},
onDrag(event) {
const dx = event.clientX - this.itemBounds.left;
const dy = event.clientY - this.itemBounds.top;
const x = Math.max(this.containerBounds.left, Math.min(this.containerBounds.right - this.itemBounds.width, event.clientX - dx));
const y = Math.max(this.containerBounds.top, Math.min(this.containerBounds.bottom - this.itemBounds.height, event.clientY - dy));
this.currentItem.style.transform = `translate(${x}px, ${y}px)`;
this.lastX = x;
this.lastY = y;
},
onDragEnd() {
if (this.lastX < this.containerBounds.left || this.lastX > this.containerBounds.right || this.lastY < this.containerBounds.top || this.lastY > this.containerBounds.bottom) {
this.currentItem.style.transform = `translate(${this.itemBounds.left}px, ${this.itemBounds.top}px)`;
}
this.currentItem = null;
this.itemBounds = null;
this.lastX = 0;
this.lastY = 0;
}
}
};
</script>
```
这里通过`getBoundingClientRect`方法获取容器的位置和大小,然后在`drag`事件中计算当前元素的位置,如果超出了容器范围就将元素移回原来的位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![xlsx](https://img-home.csdnimg.cn/images/20210720083732.png)