使用该功能需要给具体的vue组件加上对应的标识
// v-drag和dragheader
<div class="Dispose_content" v-drag>
<div class="bg_header cg_header dragheader">
</div>
</div>
通过算出鼠标相对元素的位置 移动元素到当前鼠标的相对位置
import Vue from 'vue'
// 自定义拖拽指令
Vue.directive('drag', {
// 指令的定义
bind: function (el) {
const odiv = el // 获取当前元素
odiv.classList.add('popup-border')
const oheader = el.querySelector('.dragheader') // querySelector的参数是选择器,任何选择器都可以作为它的参数
if (oheader) {
oheader.onmousedown = (e) => {
// 算出鼠标相对元素的位置
const disX = e.clientX - odiv.offsetLeft
const disY = e.clientY - odiv.offsetTop
let left = ''
let top = ''
document.onmousemove = (e) => {
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
left = e.clientX - disX
top = e.clientY - disY
// 绑定元素位置到positionX和positionY上面
// 移动当前元素
if (left <= 0) {
left = 0
} else if (left >= document.documentElement.clientWidth - odiv.offsetWidth) {
// document.documentElement.clientWidth 屏幕的可视宽度
left = document.documentElement.clientWidth - odiv.offsetWidth
}
if (top <= 50 && !odiv.className.split(' ').includes('unlimited')) {
top = 50
} else if (top >= document.documentElement.clientHeight - odiv.offsetHeight) {
// document.documentElement.clientHeight 屏幕的可视高度
top = document.documentElement.clientHeight - odiv.offsetHeight
}
odiv.style.left = left + 'px'
odiv.style.top = top + 'px'
}
document.onmouseup = (e) => {
document.onmousemove = null
document.onmouseup = null
}
if (config.currentZIndex) {
config.currentZIndex++
} else {
config.currentZIndex = 10
}
if (odiv.className.split(' ').includes('unlimited')) return
odiv.style.zIndex = config.currentZIndex
}
}
}
})
弹框拖拽功能会涉及到弹框层叠问题,当你点击某个弹框时,主动赋予比上一个弹框更高的层叠
在全局注册(register-components.js)组件时,将该js挂载到所有的组件中
主要实现方法:
/*
*@description: 设置当前的弹框层级置顶
*/
mixinPopupIndex() {
this.$nextTick(() => {
if (!(this.$el instanceof HTMLElement)) return
if (!this.$el.querySelector('.dragheader')) return
config.currentZIndex ? (config.currentZIndex++) : (config.currentZIndex = 10)
this.$el.style.zIndex = config.currentZIndex
})
}