Drag-and-drop is a common feature of dragging objects to another location, in HTML5, where drag and drop is part of the standard and any element can be dragged and dropped.
1. HTML5 Drag and drop: (Drag and drop) is part of the HTML5 standard
Drag start: ondragstart: Call a function, drag (event), which specifies the data to be dragged
Set Drag data: SetData (): Sets the data type and value of the dragged data
Put in: OnDragOver: event specifies where to place dragged data
Placement: OnDrop: Drop event occurs when the dragged data is placed
The following example drags a picture on a Web page to a specified area on a Web page:
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Drag and drop</title>6 <style>7 . Box{8 width:400px;9 Height:400px;Ten } One #box1{ A Background-color:#cccccc; - } - </style> the <Scriptsrc= "App.js"></Script> - </Head> - <Body> - <DivID= "Box1"class= "box"></Div> + <imgsrc= "1.jpg"ID= "IMG1"Height= "400px"width= "400px"> - <DivID= "MSG"></Div> + </Body> A </HTML>
The app.js used:
1 varBoxdiv, Msgdiv, IMG1;2 3Window.onload =function() {4Boxdiv = document.getElementById ("Box1");5Msgdiv = document.getElementById ("msg"));6IMG1 = document.getElementById ("IMG1");7 8 //Boxdiv.ondragenter = function (e) {9 //Showobj (e);Ten // } OneBoxdiv.ondragover =function(e) { A E.preventdefault (); - } -Img1.ondragstart =function(e) { theE.datatransfer.setdata ("Imgid", "IMG1"); - } - -Boxdiv.ondrop =function(e) { + showobj (e.datatransfer); - E.preventdefault (); + A varimg = document.getElementById (e.datatransfer.getdata ("Imgid")); at Boxdiv.appendchild (IMG); - } - } - - functionshowobj (obj) { - vars = ""; in for(varKinchobj) { -s + = k + ":" + obj[k] + "<br/>" to } +msgdiv.innerhtml =s; -}
2. HTML5 drag and drop local resources
The following example is to drag and drop a local picture to a specified area on a webpage:
1 <<doctypeHTML>2 <HTML>3 <Head>4 <MetaCharSet= "Utf-8">5 <title>Drag and drop</title>6 <style>7 #imgContainer{8 Background-color:#cccccc;9 width:500px;Ten Height:500px; One } A </style> - <Scriptsrc= "App.js"></Script> - </Head> the <Body> - <DivID= "Imgcontainer"></Div> - <DivID= "MSG"></Div> - </Body> + </HTML>
Among the app.js:
1 varImgcontainer, Msgdiv;2 3Window.onload =function(){4Imgcontainer = document.getElementById ("Imgcontainer");5Msgdiv = document.getElementById ("msg"));6 7Imgcontainer.ondragover =function(e) {8 E.preventdefault ();9 }TenImgcontainer.ondrop =function(e) { One E.preventdefault (); A - varf= e.datatransfer.files[0]; - varFileReader =NewFileReader (); theFilereader.onload =function(e) { - showobj (e.target); -imgcontainer.innerhtml = "; - } + Filereader.readasdataurl (f); - } + } A at function Showobj (obj) { -var s= ""; - For (var k in obj) { -s+=k+ ":" +obj[k]+ "<br/>"; - } -msgdiv.innerhtml =s; in}
[HTML5] Learning notes-HTML drag and drop