<template>
<div>
<div class="crop-modal" v-drag draggable="false">
<el-button>@@@@@@@</el-button>
</div>
</div>
</template>
<script>
export default {
data() {
return {};
},
//自定义指令
directives: {
drag: {
// 指令的定义
bind: function (el) {
let oDiv = el; // 获取当前元素
oDiv.onmousedown = (e) => {
// 算出鼠标相对元素的位置
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
console.log("本身的宽高", oDiv.clientHeight);
document.onmousemove = (e) => {
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
if (left <= 0) {
left = 0;
} else if (
left >=
document.documentElement.clientWidth - oDiv.clientWidth
) {
//document.documentElement.clientWidth 屏幕的可视宽度
left = document.documentElement.clientWidth - oDiv.clientWidth;
}
if (top <= 0) {
top = 0;
} else if (
top >=
document.documentElement.clientHeight - oDiv.clientHeight
) {
// document.documentElement.clientHeight 屏幕的可视高度
top = document.documentElement.clientHeight - oDiv.clientHeight;
}
oDiv.style.left = left + "px";
oDiv.style.top = top + "px";
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
};
},
},
},
};
</script>
<style lang="scss" scoped>
.crop-modal {
position: fixed;
left: 0;
top: 0;
z-index: 9999;
width: 100px;
height: 100px;
background-color: yellow;
color: green;
}
</style>
vue中div的拖拽
最新推荐文章于 2024-04-10 09:23:18 发布