<!DOCTYPE html>
<html lang="en">
<head>
<title>不知道是什么</title>
<style>
#canvas {
width: 500px;
height: 500px;
border: 1px solid red;
position: relative;
}
.node {
width: 100px;
height: 100px;
border: 1px solid green;
position: absolute;
}
</style>
</head>
<body>
<div id="canvas">
<div class="node">我可以被拖动</div>
</div>
<script>
const canvas = document.querySelector('#canvas') // 画布
const canvas_centent = canvas.getBoundingClientRect()//获取画布的大小
const node = document.querySelector('.node') // 节点
class Drag {
constructor (canvas, node ,canvas_centent) {
this.canvas = canvas
this.canvas_centent = canvas_centent
// console.log(canvas_centent);
this.canvas.ondragover = event => event.preventDefault() // 设置画布可被拖入元素
this.node = node
node.setAttribute('draggable', true) // 设置元素可被拖动
node.addEventListener('dragstart', this.dragstart.bind(this))
node.addEventListener('dragend', event => this.dragend(event))
}
dragstart (event) {
this.ondragstartX = event.x
this.ondragstartY = event.y
this.node.style.opacity = 0.382
}
dragend (event) {
// console.log(event);
const offsetX = event.x - this.ondragstartX
const offsetY = event.y - this.ondragstartY
//获取盒子的大小
const node_width = node.offsetWidth
const node_height = node.offsetHeight
//获取画布的大小
const canvas_width = canvas_centent.width
const canvas_height = canvas_centent.height
//设置盒子到鼠标的位置
let left = node.offsetLeft + offsetX
let top = node.offsetTop + offsetY
if(left > canvas_width - node_width){
left = canvas_width - node_width - 1
}
if(left < 0 ){
left = -1
}
if(top > canvas_height - node_height){
top = canvas_height - node_height - 1
}
if(top < 0){
top = -1
}
node.style.left = left + 'px'
node.style.top = top + 'px'
node.style.opacity = 1
}
}
// 设置可拖动的元素及画布
new Drag(canvas, node,canvas_centent)
</script>
</body>
</html>