1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title>图像拖动</title> 6 7 8 <style> 9 body { 10 margin: 0px;; 11 } 12 13 .container { 14 background-color: lightcyan; 15 width: 1000px; 16 height: 500px; 17 } 18 19 .box { 20 background-color: lightblue; 21 width: 400px; 22 height: 400px; 23 float: left; 24 margin: 10px;; 25 } 26 27 #box1 { 28 29 } 30 31 #box2 { 32 33 } 34 </style> 35 36 <script> 37 //初始化工作 38 function initLoad() { 39 var box1, box2, img1; 40 initElements(); 41 42 box1.ondragenter = ondragenter; 43 box2.ondragenter = ondragenter; 44 45 box1.ondragover = ondragover; 46 box2.ondragover = ondragover; 47 48 box1.ondrop = ondrop; 49 box2.ondrop = ondrop; 50 51 box1.ondragleave = ondragleave; 52 53 img1.ondragstart = ondragstart; 54 img1.ondragend = function (event) { //结束拖动 55 showMsg("end"); 56 } 57 58 function ondragenter(event) { 59 showMsg("ondragenter 拖动物体进入啦(即一开始拖动进入那一刻)"); 60 } 61 62 //物体拖动进入中 63 function ondragover(event) { 64 showMsg("ondragover 有物体拖动在上面(即一直按住左键拖动)"); 65 event.preventDefault(); //阻止浏览器默认的属性 66 } 67 68 //物体拖动放置时 69 function ondrop(event) { 70 showMsg("ondrop 物体放置时(即松开左键)"); 71 event.preventDefault(); 72 73 //showMsg(event); 74 showMsg(event.clientX) 75 showMsg(event.clientY) 76 77 //获取该节点id 78 var id = event.dataTransfer.getData("dataId"); 79 var childNode = getElement(id); //获取节点 80 event.target.appendChild(childNode);//添加节点 81 } 82 83 //拖动离开 84 function ondragleave(event) { 85 showMsg("ondragleave 离开啦"); 86 } 87 88 89 //图像拖动时 90 function ondragstart(event) { 91 showMsg("图像被拖动中...") 92 //设置传递的数据封装 93 event.dataTransfer.setData("dataId", event.target.id); 94 } 95 96 //初始化元素 97 function initElements() { 98 showMsg("初始化元素"); 99 box1 = getElement("box1"); 100 box2 = getElement("box2"); 101 img1 = getElement("img1"); 102 } 103 104 //根据id获取元素的简写 105 function getElement(id) { 106 return document.getElementById(id); 107 } 108 109 } 110 111 //打印信息 112 function showMsg(obj) { 113 console.log(obj); 114 } 115 function showMsg(msg) { 116 console.log(msg); 117 } 118 119 120 </script> 121 122 </head> 123 <body onload="initLoad()"> 124 125 <div class="container"> 126 <p>这是一个网页上的图像拖动测试</p> 127 128 <div id="box1" class="box"></div> 129 <div id="box2" class="box"></div> 130 <img src="images/html5.png" id="img1" alt="可以拖动我" draggable="true"/><!--img 默认可以拖拽--> 131 </div> 132 133 </body> 134 </html>
时间: 2024-10-21 15:28:23