Home > Web Front-end > H5 Tutorial > body text

Use html5 to implement simple drag function

王林
Release: 2020-12-10 16:59:04
forward
4412 people have browsed it

Use html5 to implement simple drag function

The specific method is as follows:

1. Set the draggable attribute of the object element to true (draggable="true"). It should also be noted that the a element and img element must specify href;

2. Write event processing code related to drag and drop:

(Learning video sharing: html video tutorial)

Use html5 to implement simple drag function

3. Case implementation code:

(1) HTML code segment:

<div id="cun" οndrοp="drop(event)" οndragοver="allowDrop(event)"></div>
<br />
<img  src="img/html5.png" id="tuo" draggable="true" οndragstart="drag(event)"/ alt="Use html5 to implement simple drag function" >
Copy after login

(2) CSS code segment:

#tuo{
	width: 540px;
	height: 320px;
	background: #e54d26;
}
#cun{
	width: 540px;
	height: 320px;
	border: 2px solid #d2d2d2;
	box-shadow: 1px 4px 8px #646464;
}
img{
	width: 500px;
	height: 280px;
}
Copy after login

(3) JavaScript code segment:

function allowDrop(ev){
	//不执行默认处理(拒绝被拖放)
	ev.preventDefault();
};
function drag(ev){
	//使用setData(数据类型,携带的数据)
	//方法将要拖放的数据存入dataTransfer对象
	ev.dataTransfer.setData("Text",ev.target.id);
};
function drop(ev){
	//不执行默认处理(拒绝被拖放)
	ev.preventDefault();
	//使用getData()获取到数据,然后赋值给data
	var data = ev.dataTransfer.getData("Text");
	//使用appendChild方法把拖动的节点放到元素节点中成为其子节点
	ev.target.appendChild(document.getElementById(data));
};
Copy after login

4. The effect achieved is as follows:

(1) Before dragging and dropping:

Use html5 to implement simple drag function

(2) After dragging and dropping

Use html5 to implement simple drag function

Related recommendations: html5 tutorial

The above is the detailed content of Use html5 to implement simple drag function. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template