js学习笔记之把一个div拖动到另一个div上面,这也是之前看到的例子,不知道出处了
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<div id="div1" style="width:300px; height:300px; background-color:#0F0" οndrοp="drop(event)" οndragοver="allowDrop(event)"></div>
<div id="drag1" style="width:200px; height:200px; background-color:#999" draggable="true" οndragstart="drag(event)" οndrοp="drop(event)" οndragοver="allowDrop(event)">这个可以拖动到上面绿色的div里面</div>
</body>
<script type="text/javascript">
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
ev.dataTransfer.setData("Text",ev.target.id);
}
function drop(ev)
{
ev.preventDefault();
var data=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
}
</script>
</html>
初始化:
拖动后: