Home >Web Front-end >H5 Tutorial >Use html5 to implement simple drag function

Use html5 to implement simple drag function

王林
王林forward
2020-12-10 16:59:044454browse

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" >

(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;
}

(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));
};

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete