指令代码
export default {
bind(el, binding) {
let startX, startY, initialX, initialY;
function onMouseDown(e) {
startX = e.clientX;
startY = e.clientY;
initialX = el.offsetLeft;
initialY = el.offsetTop;
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
e.preventDefault();
}
function onMouseMove(e) {
const moveX = e.clientX - startX;
const moveY = e.clientY - startY;
const elRect = el.getBoundingClientRect();
const elementWidth = elRect.width;
const elementHeight = elRect.height;
let newLeft = initialX + moveX;
let newTop = initialY + moveY;
const maxRight = window.innerWidth - elementWidth;
const maxBottom = window.innerHeight - elementHeight - 1;
if (binding.value?.axisy) {
newLeft = maxRight;
} else {
newLeft = Math.max(0, Math.min(newLeft, maxRight));
}
if (binding.value?.axisx) {
newTop = maxBottom;
} else {
newTop = Math.max(110, Math.min(newTop, maxBottom)); // 防止溢出,并且不让顶部少于 110px
}
el.style.left = `${newLeft}px`;
el.style.top = `${newTop}px`;
if (binding.value?.callback) {
binding.value.callback({
top: newTop,
bottom: maxBottom - newTop,
left: newLeft,
right: maxRight - newLeft,
});
}
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
el.addEventListener('mousedown', onMouseDown);
},
};
使用过程
1.在src下新建directive文件夹,然后在directive新建draggable文件夹,在文件夹新建index文件,最后复制上方代码
2.在directive下新建index.js文件,文件代码
import drag from "./draggable/index";
const install = function (Vue) {
//拖拽指令
Vue.directive("draggable", drag);
};
if (window.Vue) {
Vue.use(install); // eslint-disable-line
}
export default install;
3.在 main.js文件中
import directive from "./directive"; // directive
Vue.use(directive);
4.使用方法
<template>
<div class="wrap fec">
<transition name="slide-fade">
<div
class="alarmBall"
v-draggable="AlarmBallDraggable"
>
<img class="w100 h00" src="@/assets/images/alarmball.gif" alt="" />
</div>
</transition>
</div>
</template>
<script>
export default {
props: {},
data() {
return {
//信号球拖拽配置
AlarmBallDraggable: {
callback: (position) => {
//position位置信息
},
},
};
},
computed: {},
watch: {},
methods: {
},
mounted() {},
beforeDestroy() {},
created() {},
};
</script>
<style lang="scss" scoped>
.alarmBall {
position: fixed;
right: 20px;
bottom: 70px;
width: 88px;
height: 88px;
z-index: 9999;
}
</style>