<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.27.0/moment.js"></script>
<style>
.box{
width: 100px;
height: 100px;
background-color: skyblue;
position: relative;
}
</style>
</head>
<body>
<div id="app">
<div class="box" @mousedown="move"></div>
</div>
<script>
new Vue({
el: '#app',
data() {
return {
positionX:'',
positionY:''
}
},
methods: {
move(e) {
console.log(e)
let odiv = e.target; //获取目标元素
console.log(odiv.offsetLeft)
// //算出鼠标相对元素的位置
let disX = e.clientX - odiv.offsetLeft;
console.log(disX)
let disY = e.clientY - odiv.offsetTop;
document.onmousemove = (e) => { //鼠标按下并移动的事件
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
//绑定元素位置到positionX和positionY上面
this.positionX = top;
this.positionY = left;
//移动当前元素
odiv.style.left = left + 'px';
odiv.style.top = top + 'px';
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
}
},
})
</script>
</body>
</html>
点击进行拖拽移动
最新推荐文章于 2022-08-30 16:15:16 发布