0
点赞
收藏
分享

微信扫一扫

js实现对一个元素进行鼠标拖动操作

四月Ren间 2022-10-28 阅读 190


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>vue</title>


</head>
<style>
*{margin: 0;padding:0;}
#app{
position: relative;
top: 10px;
left: 10px;
width: 80px;
height: 80px;
background: #666;
}
</style>
<body>
<div id="app" @mousedown="move">
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="./js/vue.min.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
positionX: 0,
positionY: 0
},
methods: {
move(e){
let odiv = e.target;
let x = e.clientX - odiv.offsetLeft;
let y = e.clientY - odiv.offsetTop;
console.log(odiv.offsetLeft,odiv.offsetTop)
document.onmousemove = (e) => {
let left = e.clientX - x;
let top = e.clientY - y;
this.positionX = left;
this.positionY = top;
//console.log(document.documentElement.clientHeight,odiv.offsetHeight)
if (left <= 0) {
left = 0;
} else if (left >= document.documentElement.clientWidth - odiv.offsetWidth){
left = document.documentElement.clientWidth - odiv.offsetWidth;
}
if (top <= 0) {
top = 0;
} else if (top >= document.documentElement.clientHeight - odiv.offsetHeight){
top = document.documentElement.clientHeight - odiv.offsetHeight
}
odiv.style.left = left + "px";
odiv.style.top = top + "px"
}
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null
}
}
}
})
</script>
</html>

很多网上的给的那篇拿来运行发现报错,原因是少了引入vue。

举报

相关推荐

0 条评论