強烈推薦閱讀'The HTML5 drag and drop disaster'。
<!DOCTYPE html>
<html>
<head>
<style>
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
height: 100%;
}
section {
height: 100%;
}
div {
width: 40px;
height: 40px;
position: absolute;
background-color: #000;
}
</style>
</head>
<body>
<section ondragenter="return drag_enter(event)" ondrop="return drag_drop(event)" ondragover="return drag_over(event)">
<div id="item" draggable="true" ondragstart="return drag_start(event)"></div>
</section>
<script>
function drag_enter(action)
{
action.preventDefault();
return true;
}
function drag_over(action)
{
action.preventDefault();
}
function drag_start(action)
{
action.dataTransfer.effectAllowed = 'move';
action.dataTransfer.setData('id', action.target.getAttribute('id'));
return true;
}
function drag_drop(action)
{
var id = action.dataTransfer.getData('id');
var element = document.getElementById(id);
element.style.top = action.clientY + 'px';
element.style.left = action.clientX + 'px';
if (action.stopPropagation)
{
action.stopPropagation();
}
return false;
}
</script>
</body>
</html>
進一步閱讀
HTML Drag and Drop API
Native HTML5 Drag and Drop
Native Drag and Drop
我真的不研究這個,但我不知道,如果你能在綁定和ondragstart解除綁定事件它在漸進。 –