As mentioned above, there are two roles involved. One is a draggable element named node. What’s the other one? If an element can be dragged, when it stops, it must be attached to something, and this character is named canvas.
Through the scene, two roles are analyzed, and then the functions of the two roles can be obtained.
Nodes:
- Can be dragged.
- Drag to start the event.
- Drag to end the event.
Canvas:
- In which elements can be placed.
As above, the core functionality has been determined, and it’s up to you to see how simple the code is.
<! DOCTYPEhtml>
<html lang="en">
<head>
<title>Document</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">I can be dragged</div>
</div>
<script>
const canvas = document.querySelector('#canvas') / / the canvas
const node = document.querySelector('.node') / / the node
class Drag {
constructor (canvas, node) {
this.canvas = canvas
this.canvas.ondragover = event= > event.preventDefault() // Sets the canvas to be dragged in elements
this.node = node
node.setAttribute('draggable'.true) // Set elements can be dragged
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) {
const offsetX = event.x - this.ondragstartX
const offsetY = event.y - this.ondragstartY
const node = this.node
const left = node.offsetLeft + offsetX
const top = node.offsetTop + offsetY
node.style.left = left + 'px'
node.style.top = top + 'px'
node.style.opacity = 1}}// Set draggable elements and canvas
new Drag(canvas, node)
</script>
</body>
</html>
Copy the code
Above, is all implementation, all copy code, can be easily verified. If you have any questions, leave a comment.