Home > Article > Web Front-end > How to implement drag and drop events in native js (code)
The content of this article is about how to implement drag and drop events (code) in native js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> .box{ width:200px; height:200px; background-color: red; position: absolute; left:0; top:0; } </style> </head> <body> <p class='box'></p> <script> var box = document.querySelector('.box'); box.onmousedown = function(e){ var event = e || window.event; var target = event.target || event.srcElement; var disX = event.clientX - target.offsetLeft; var disY = event.clientY - target.offsetTop; document.onmousemove = function(event){ // 注意:这里要有自己的事件对象 target.style.left = event.clientX - disX + 'px'; target.style.top = event.clientY - disY + 'px'; document.onmouseup = function(){ document.onmousedown = null; document.onmousemove = null; } } } </script> </body> </html>
Related recommendations:
js control file dragging and get the drag content implementation code
js simple table Drag_javascript skills
Native JS to achieve drag and drop image effect_javascript skills
The above is the detailed content of How to implement drag and drop events in native js (code). For more information, please follow other related articles on the PHP Chinese website!