随手记录
import Vue from 'vue'
const drag = Vue.directive('drag', {
inserted: function (el, data) {
let firstTime = null
let lastTime = null
el.onmousedown = function (e) {
if (e.target.id === data.value || !data.value) {
firstTime = new Date().getTime()
el.style.position = 'absolute'
var disx = e.pageX - el.offsetLeft
var disy = e.pageY - el.offsetTop
document.onmousemove = function (e) {
let positionLeft = e.pageX - disx
let positionTop = e.pageY - disy
const winWidth = window.innerWidth
const winHeight = window.innerHeight
if (positionLeft <= 0) positionLeft = 0
if (positionTop <= 0) positionTop = 0
if (positionLeft > winWidth - el.offsetWidth) positionLeft = winWidth - el.offsetWidth
if (positionTop > winHeight - el.offsetHeight) positionTop = winHeight - el.offsetHeight
el.style.left = positionLeft + 'px'
el.style.top = positionTop + 'px'
}
document.onmouseup = function (e) {
lastTime = new Date().getTime()
document.onmousemove = document.onmouseup = null
if ((lastTime - firstTime) > 200) {
document.getElementById('dragbtn').setAttribute('data-flag', true)
} else {
document.getElementById('dragbtn').setAttribute('data-flag', false)
}
}
}
}
}
})
main.js
export default drag
// 导出在main.js引用
import drag from '@/utils/drag
vue页面
// 使用
<div v-drag id="dragbtn"></div>
// 获取自定义的属性
const isClick = document.getElementById('dragbtn').getAttribute('data-flag')
if (isClick !== 'true') {
// 点击事件业务处理
} else {
}