elementui中el-dialog拖拽不能超出指定元素
时间: 2023-07-30 08:11:51 浏览: 165
要实现el-dialog拖拽不能超出指定元素,可以使用Vue.js的指令v-dialog-drag,结合CSS的position属性和JS的计算方法来实现:
1. 在el-dialog中添加一个指令v-dialog-drag,如下所示:
```
<el-dialog v-dialog-drag="{target:'.target-element'}"></el-dialog>
```
其中,target属性指定了拖拽不能超出的目标元素选择器。
2. 在CSS中设置目标元素的position属性为relative或absolute,如下所示:
```
.target-element {
position: relative;
}
```
3. 在Vue.js的自定义指令中,获取目标元素的位置和大小,计算el-dialog的位置,实现拖拽不能超出目标元素的效果,代码如下:
```
Vue.directive('dialogDrag', {
bind(el, binding, vnode) {
const dialogHeaderEl = el.querySelector('.el-dialog__header');
const dragDom = el.querySelector('.el-dialog');
const targetDom = document.querySelector(binding.value.target);
const targetRect = targetDom.getBoundingClientRect();
dialogHeaderEl.style.cursor = 'move';
// 获取el-dialog的位置
const getDialogPosition = (event) => {
const dragDomRect = dragDom.getBoundingClientRect();
const targetLeft = targetRect.left + window.pageXOffset;
const targetTop = targetRect.top + window.pageYOffset;
const maxLeft = targetLeft + targetDom.clientWidth - dragDomRect.width;
const maxTop = targetTop + targetDom.clientHeight - dragDomRect.height;
let left = dragDomRect.left + event.clientX - startX;
let top = dragDomRect.top + event.clientY - startY;
left = Math.max(targetLeft, Math.min(left, maxLeft));
top = Math.max(targetTop, Math.min(top, maxTop));
return {left, top};
}
let startX = 0;
let startY = 0;
let dialogLeft = 0;
let dialogTop = 0;
let dragging = false;
// 鼠标按下事件
const handleMousedown = (event) => {
startX = event.clientX;
startY = event.clientY;
dialogLeft = parseFloat(getComputedStyle(dragDom).left);
dialogTop = parseFloat(getComputedStyle(dragDom).top);
dragging = true;
}
// 鼠标移动事件
const handleMousemove = (event) => {
if (dragging) {
const {left, top} = getDialogPosition(event);
dragDom.style.left = `${left}px`;
dragDom.style.top = `${top}px`;
}
}
// 鼠标释放事件
const handleMouseup = () => {
dragging = false;
}
dialogHeaderEl.addEventListener('mousedown', handleMousedown);
document.addEventListener('mousemove', handleMousemove);
document.addEventListener('mouseup', handleMouseup);
}
});
```
这样,el-dialog就可以在指定元素内拖拽,不能超出目标元素。
阅读全文