1 2 3 4 5 拖放API 6 31 32 33 34 請拖放 35 36 37 94 95 ...
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>拖放API</title> 6 <style> 7 [id='dragme']{ 8 width: 100px; 9 height: 100px; 10 color: #fff; 11 text-align: center; 12 line-height: 100px; 13 background-color:#aaa; 14 user-select: none; 15 cursor:pointer; 16 } 17 [id='text']{ 18 width: 300px; 19 height: 300px; 20 margin-top: 20px; 21 } 22 .border{ 23 border: 1px solid #aaa; 24 border-radius:.2em; 25 box-shadow:2px 2px 3px #aaa; 26 } 27 .hide{ 28 display: none; 29 } 30 </style> 31 </head> 32 <body> 33 <div class="content"> 34 <div class="border" id="dragme" draggable="true">請拖放</div> 35 <div class="border" id="text"></div> 36 </div> 37 <script> 38 var page = { 39 init : function(){ 40 this.draggable(); 41 this.perDefault(); 42 }, 43 draggable : function(){ 44 var source = document.getElementById('dragme'), 45 dest = document.getElementById('text'), 46 dragIcon = document.createElement('img'), 47 n = 1; 48 dragIcon.src = ''; 49 //拖放開始 50 source.addEventListener('dragstart', function(ev){ 51 //向dataTransfer追加數據 52 var dt = ev.dataTransfer; 53 dt.effectAllowed = 'all'; 54 dt.setData("text/plain", n); 55 //自定義拖放圖標 56 dt.setDragImage(dragIcon, -10, -10); 57 },false); 58 //拖放結束 59 dest.addEventListener('dragend', function(ev){ 60 ev.preventDefault(); 61 },false) 62 //被拖放 63 dest.addEventListener('drop', function(ev){ 64 n++; 65 //從dataTransfer對象獲取數據 66 var dt = ev.dataTransfer, 67 text = dt.getData("text/plain"); 68 dest.textContent += text+' '; 69 //阻止預設行為(拒絕被拖放) 70 ev.preventDefault(); 71 //阻止事件冒泡 72 ev.stopPropagation(); 73 },false) 74 //被拖放的元素在本元素範圍內移動 75 //dropEffect拖放時的視覺效果/圖標 76 dest.addEventListener("dragover", function(ev){ 77 var dt = ev.dataTransfer; 78 dt.dropEffect = 'link'; 79 ev.preventDefault(); 80 },false) 81 }, 82 //設置頁面屬性,阻止預設行為 83 perDefault : function(){ 84 document.ondragover = function(e){ 85 e.preventDefault(); 86 } 87 document.indrop = function(e){ 88 e.preventDefault(); 89 } 90 } 91 } 92 window.onload = page.init(); 93 </script> 94 </body> 95 </html>