拖拽
一,拖拽浏览器本身元素
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .container{ 8 width: 100px; 9 height: 100px; 10 background-color: #abcdef; 11 margin-top: 5px; 12 } 13 </style> 14 <script src="../../node_modules/jqueryui/external/jquery/jquery.js"></script> 15 </head> 16 <body> 17 <div class="container"> 18 <div id="text" draggable="true">drag me</div> 19 </div> 20 <div id="target-container" class="container"> 21 </div> 22 <script src="main.js"></script> 23 </body> 24 </html>
1 (function () { 2 3 4 function addListeners() { 5 6 $("#text").on("dragstart", function (e) { 7 e.originalEvent.dataTransfer.setData("text/plain", this.id); 8 }); 9 $(".container").on("dragover", function (e) { 10 e.preventDefault(); 11 }).on("drop", function (e) { 12 e.preventDefault(); 13 e.stopPropagation(); 14 15 var element = document.getElementById(e.originalEvent.dataTransfer.getData("text/plain")); 16 if (element.parentNode) { 17 element.parentNode.removeChild(element); 18 } 19 this.appendChild(element); 20 }) 21 } 22 23 function init() { 24 addListeners(); 25 } 26 27 init(); 28 })();
二,拖拽外部文件到浏览器
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 #target{ 8 width: 400px; 9 height: 400px; 10 background: #abcdef; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="target"></div> 16 <script src="main.js"></script> 17 </body> 18 </html>
1 (function () { 2 3 var target = document.querySelector("#target"); 4 5 target.addEventListener("dragover", function (e) { 6 e.preventDefault(); 7 }); 8 9 target.addEventListener("drop", function (e) { 10 e.preventDefault(); 11 12 var files = e.dataTransfer.files; 13 var reader; 14 15 if (files && files.length) { 16 var file = files[0]; 17 switch (file.type) { 18 case "text/plain": 19 reader=new FileReader(); 20 reader.onload=function () { 21 target.innerHTML=reader.result; 22 }; 23 reader.readAsText(file); 24 break; 25 case "image.jpeg": 26 case "image.jpg": 27 reader=new FileReader(); 28 reader.onload=function () { 29 target.innerHTML="<img src='"+reader.result+"'>"; 30 }; 31 reader.readAsDataURL(file); 32 break; 33 default: 34 console.log(file); 35 break; 36 } 37 } 38 }); 39 })();
myGitgub https://github.com/mfx55
希望我的博客能帮到你