使用原生js实现简单的拖拽事件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>Title</title> <style> #drag-el { 100px; height: 100px; background-color: greenyellow; } #drop-el { 200px; height: 200px; background-color: antiquewhite; } </style> </head> <body> <div id="drop-el"></div> <div id="drag-el" draggable="true"> 可拖拽元素 </div> <script> window.onload = function () { var dropEl = $('#drop-el'); var dragEl = $('#drag-el');
//设置关联数据 dragEl.addEventListener("dragstart", dragstartHandle);
//禁止默认事件,使其可拖放 dropEl.addEventListener("dragenter", preventDefault); dropEl.addEventListener("dragover", preventDefault);
//鼠标释放,在拖放目标上接受数据并处理 dropEl.addEventListener("drop", dropHandle); function dropHandle(event) { event.preventDefault(); var data = event.dataTransfer.getData("Text"); event.target.appendChild($("#" + data)); } function dragstartHandle(event) { event.dataTransfer.setData("Text", event.target.id); } function preventDefault(event) { console.log(event.type); event.preventDefault(); } function $(sel) { return document.querySelector(sel); } } </script> </body> </html>