<!-- 演示demo 鼠标拖放 -->
<template>
<div class="demo" v-drag>
<ul>
<li>
可拖动
</li>
<li>vue</li>
<li>vue2</li>
</ul>
</div>
</template>
<script>
export default {
directives: {
drag: function(el) {
let dragBox = el;
dragBox.onmousedown = (e) => {
//算出鼠标相对元素的位置
let disX = e.clientX - dragBox.offsetLeft;
let disY = e.clientY - dragBox.offsetTop;
document.onmousemove = (e) => {
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
//移动当前元素
dragBox.style.left = left + "px";
dragBox.style.top = top + "px";
};
document.onmouseup = (e) => {
//鼠标弹起来的时候不再移动
document.onmousemove = null;
//预防鼠标弹起来后还会循环(即预防鼠标放上去的时候还会移动)
document.onmouseup = null;
};
};
},
},
};
</script>
<style lang="less" scoped>
.demo {
padding: 50px;
width: 200px;
position: fixed;
z-index: 10;
top: 50%;
right: 50%;
background-color: #ffffff;
cursor: move;
}
</style>
vue2 实现鼠标移动拖放
最新推荐文章于 2024-08-06 09:25:20 发布