定义的全局指令:
使用方式
<!-- 变成了一个可以被拖拽的元素 啦啦啦 -->
<div v-drag></div>
import Vue from "vue"
Vue.directive("drag", {
bind(el) {
el.onmousedown = function (event) {
var event = event || window.event; //兼容IE浏览器
// 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
var diffX = event.clientX - el.offsetLeft;
var diffY = event.clientY - el.offsetTop;
if (typeof el.setCapture !== 'undefined') {
el.setCapture();
}
document.onmousemove = function (event) {
var event = event || window.event;
var moveX = event.clientX - diffX;
var moveY = event.clientY - diffY;
if (moveX < 0) {
moveX = 0
} else if (moveX > window.innerWidth - el.offsetWidth) {
moveX = window.innerWidth - el.offsetWidth
}
if (moveY < 0) {
moveY = 0
} else if (moveY > window.innerHeight - el.offsetHeight) {
moveY = window.innerHeight - el.offsetHeight
}
el.style.left = moveX + 'px';
el.style.top = moveY + 'px'
}
document.onmouseup = function (event) {
this.onmousemove = null;
this.onmouseup = null;
//修复低版本ie bug
if (typeof el.releaseCapture != 'undefined') {
el.releaseCapture();
}
}
}
}
})
网友评论