HTML5学习—— 拖放

开发工具:IntelliJ IDEA

实现效果:将img1拖至div1 或div2

div1 div2
img1  
 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style type="text/css">
 7         .box {
 8             width:390px;
 9             height:400px;
10             float: left;
11         }
12         #p1 {   background-color: lightgrey;}
13         #p2 {  background-color: darksalmon }
14 
15     </style>
16 
17     <script>
18         var pl1,msg,pl2,img1;
19         //ondargstart 当元素被拖动时会发生什么
20         //ondargover 在何处放置被拖放的数据
21         //ondrop 当放置被拖数据时,触发该事件
22         //prenventDefault()避免浏览器对数据的默认处理
23         //drop事件的默认行为是以链接形式打开
24         window.onload=function()
25         {
26             pl1=document.getElementById("p1");
27             msg=document.getElementById("msg");
28             pl2=document.getElementById("p2");
29             img1=document.getElementById("img1");
30             pl1.ondragover=function(e){
31                 e.preventDefault();
32             }
33             pl2.ondragover=function(e){
34                 e.preventDefault();
35             }
36 
37             img1.ondragstart=function(e)
38             {
39                 e.dataTransfer.setData("imgId","img1")
40             }
41 
42             pl1.ondrop=drophandler;
43             pl2.ondrop=drophandler;
44         }
45         function drophandler(e)
46         {
47             e.preventDefault();
48             var img=document.getElementById(e.dataTransfer.getData("imgId")) ;
49             e.target.appendChild(img);
50         }
51 //        function showmsg(obj)
52 //        {
53 //            var s;
54 //            for (var k in obj)
55 //            {
56 //                s+=k+":"+obj[k]+"<br/>";
57 //
58 //            }
59 //            msg.innerHTML=s;
60 //        }
61     </script>
62 </head>
63 <body marginheight="0px" marginwidth="0px">
64 <div id="p1" class="box"></div>
65 <div id="p2" class="box"></div>
66 <div id="msg"  style="float: left;"></div>
67 <img src="media/img1.jpg" id="img1" draggable="true" />
68 
69 </body>
70 </html>
View Code
原文地址:https://www.cnblogs.com/NoteofEveryDay/p/4585817.html