日期:2014-05-16  浏览次数:20705 次

HTML5 实现拖拽


如图

可以从第一个方框拖拽花色到第二个方框中。


也可以再拖动回来。


具体代码实现

index.html

<!DOCTYPE HTML>
<html>
<head>
<meta charset=utf-8>
<title>HTML5 Drag && Drop Demo</title>
<link rel="stylesheet" href="css/main.css"></link>
<script>
function DragHandler(target, e) {
        e.dataTransfer.setData('Text', target.id);
    }
 
    function DropHandler(target, e) {
       var id = e.dataTransfer.getData('Text');
       target.appendChild(document.getElementById(id));
       e.preventDefault();
    }

</script>
</head>
<body>
<header>
<h1>HTML5 Drag & Drop Demo</h1>
</header>
<div id="dndcontainer">
<div ondrop="DropHandler(this,event)" ondragenter="return false" ondragover="return false" class="dndbox">
<img src="images/item-1.png" id="club" ondragstart="DragHandler(this,event)" width="75" height="75" border="0" alt=""/>
<img src="images/item-2.png" id="heart" ondragstart="DragHandler(this,event)" width="75" height="75" border="0" alt=""/>
<img src="images/item-3.png" id="spade" ondragstart="DragHandler(this,event)" width="75" height="75" border="0" alt=""/>
<img src="images/item-4.png" id="diamond" ondragstart="DragHandler(this,event)" width="75" height="75" border="0" alt=""/>
</div>
<div ondrop="DropHandler(this,event)" ondragenter="return false" ondragover="return false" class="dndbox"></div>
</div>
</body>
</html>

main.css

.dndbox
{
	width:300px;
	height:300px;
	border:1px solid #000;
}