Home >Web Front-end >H5 Tutorial >How to implement drag and drop of images in HTML5
Today I will share with you the usage of drag and drop elements in HTML5. It has certain reference value and I hope it will be helpful to everyone.
[Recommended courses: HTML5 Tutorial##]
Drag (drag) and drop (drop) is a common HTML5 special effect on the page. What it means is to grab the object and then drag and drop it to another a location. In HTML5, any element can be dragged and dropped, so in the following article, I will tell you in detail how to achieve the drag effect through examples.
Knowledge points required for drag and drop effects
draggable
Specifies whether an element can be dragged Generally, links and pictures are draggable by default. true: Specifies that the element is draggable. false: Specifies that the element is not draggable. auto: Use the browser’s default features.Events triggered when dragging and dropping elements
ondragstart: Events triggered when dragging elements start ondrag: Triggered when elements are being dragged Eventondragend: Event triggered after the user completes dragging the elementEvent triggered when the target is released
ondragenter: The dragged element enters Events triggered when dragging the rangeondragover: Indicates where the event is triggered when the dragged data is placed. ondragleave: Event triggered when the dragged element leaves the drag rangeondrop: When the mouse leaves the drag and drop elementCase sharing: Place the picture into the box
(1) Set the element to be draggable<img id="drag1" src=images/1.jpg" draggable="true" alt="How to implement drag and drop of images in HTML5" >(2) What happens when the element is dragged (drag) dataTransfer: Save the dragged data
function drag(event) { event.dataTransfer.setData("Text",event.target.id); }(3) Drag the element to the specified position (drop)
function drop(event) { event.preventDefault();//取消浏览器的默认行为 var data=event.dataTransfer.getData("Text");//获取指定格式的数据 event.target.appendChild(document.getElementById(data)); }
Complete code
<body> <div id="box" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <img src="images/1.jpg" id="drag1" draggable="true" ondragstart="drag(event)" alt="How to implement drag and drop of images in HTML5" > <script> function allowDrop(event) { event.preventDefault();//取消事件默认行为 } //拖 function drag(event){ event.dataTransfer.setData("Text",event.target.id) } //放 function drop(event){ event.preventDefault(); var data=event.dataTransfer.getData("text"); event.target.appendChild(document.getElementById(data)) } </script> </body>
Rendering
Summary: The above is this This is the entire content of this article. I hope this article will be helpful to everyone in learning to drag and drop elements.The above is the detailed content of How to implement drag and drop of images in HTML5. For more information, please follow other related articles on the PHP Chinese website!