前端vue项目中,经常会有弹框拖拽的需求,下面介绍常用方法:
1.如果你使用的是elementPlus插件的el-dialog组件,只需要增加draggable属性即可,代码如下:
<el-dialog
v-model="showDiloag"
width="500"
draggable
></e--dialog>
2.如果不使用ele 的组件,自己写弹框,那么可以自定义指令,代码如下(vue3):
drag.js文件:
const drag = {
mounted(el, binding) {
el.style.position = "absolute";
const data = binding.value || { x: 0, y: 0, zIndex: 99999 };
let { x, y, zIndex = 99999 } = data;
el.style.left = x + "px";
el.style.top = y + "px";
el.style.zIndex = zIndex;
let isDragging = false;
let baseMousePosition = { x: 0, y: 0 };
let dom = data.targetRef || document.getElementById(data.targetId) || el;
dom.style.cursor = "move";
const onDragStart = (e) => {
if (e.button === 0) {
isDragging = true;
baseMousePosition.x = e.pageX;
baseMousePosition.y = e.pageY;
window.addEventListener("mousemove", onDraging);
}
};
const onDragEnd = (e) => {
isDragging = false;
x = parseInt(el.style.left);
y = parseInt(el.style.top);
window.removeEventListener("mousemove", onDraging);
};
const onDraging = (e) => {
if (isDragging) {
el.style.left = e.pageX - baseMousePosition.x + x + "px";
el.style.top = e.pageY - baseMousePosition.y + y + "px";
}
};
dom.addEventListener("mousedown", onDragStart);
window.addEventListener("mouseup", onDragEnd);
},
};
const directives = {
install: function (app) {
app.directive('drag', drag)
}
}
export default directives
vue文件使用:
<script setup>
import { ref } from "vue";
const dragRef = ref()
const dragOptions= ref({
x: 100,
y: 200,
targetRef: dragRef,
})
</script>
<template>
<div v-drag="dragOptions" class="dialog">
<div class="dialog_header" ref="dragRef">弹框标题</div>
<div class="dialog_content">弹框内容</div>
</div>
<template>
这里的dragOptions就是配置项,x和y是弹框的初始位置的left和top值,targetRef的值是你希望鼠标在哪个dom元素可以拖拽,如果不传,就默认在整个弹框范围,都可以拖拽。