实现拖拽功能,主要有以下几个步骤:
1. 鼠标点击时获取鼠标的坐标,并开始监听鼠标的移动和鼠标的松开动作
2. 鼠标移动时获取当前坐标,并计算相对于鼠标点击时坐标的偏移值,并修改弹窗的偏移量
3. 鼠标松开时停止所有监听,并保存弹窗当前的位置
直接上代码:
<template>
<a-modal
v-model:visible="modelVisible"
:style="style"
>
<template #title>
<-- 此处我只在弹窗的title部分添加了拖拽功能-->
<div style="padding: 16px 24px" @mousedown="mouseDown" @mouseup="mouseUp">
<slot name="title"></slot>
</div>
</template>
<template #footer>
<slot name="footer"></slot>
</template>
<slot></slot>
</a-modal>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
data () {
return {
modelVisible: false,
style: null,
initX: null,
initY: null,
left: 0, //移动时相对于鼠标点击时坐标的偏移位置
top: 0,
lastleft: 0, // 每次拖拽后弹窗的位置
lasttop: 0
}
},
methods: {
mouseDown (e) {
this.initX = e.clientX;
this.initY = e.clientY;
document.addEventListener("mousemove", this.mouseMove, false)
document.addEventListener("mouseup", this.mouseUp, false)
},
mouseUp () {
//拖拽后弹窗最后一次所在位置为前一次拖拽最后的位置加上这次拖拽的偏移量
this.lastleft = this.lastleft + this.left;
this.lasttop = this.lasttop + this.top;
this.style = "left:" + this.lastleft + "px;margin-top: " + this.lasttop + "px"
document.removeEventListener("mousemove", this.mouseMove, false)
document.removeEventListener("mouseup", this.mouseUp, false)
this.initX = null;
this.initY = null;
},
mouseMove (e) {
this.left = (e.clientX - this.initX);
this.top = (e.clientY - this.initY)
this.style = "left:" + this.lastleft + "px;margin-top: " + this.lasttop + "px" + ";transform:translate(" + this.left + "px," + this.top + "px)"
},
}
})
</script>
<style lang="scss">
.ant-modal-header {
padding: 0;
}
</style>
此代码是基于vue3写的。