應用於被拖拽元素的事件
ondrag:整個拖拽過程都會觸發
ondragstart:拖拽開始時觸發
ondragleave:鼠標離開拖拽目標時觸發
ondragend:拖拽結束時觸發
應用於目標元素的事件
ondragenter:拖拽元素進入時觸發
ondragover:停留在目標元素上時觸發
ondrop:在目標上鬆開鼠標時觸發
ondragleave:鼠標離開拖拽目標時觸發
演示代碼
<!DOCTYPE html>
<html>
<head>
<title>拖拽</title>
<meta charset="utf-8" />
</head>
<style>
div{
height: 400px;
width: 400px;
border: 1px solid black;
float: left;
margin: 30px;
}
p{
width: 100%;
background-color: aqua;
text-align: center;
}
</style>
<body>
<div>
<p id="p1" draggable="true">拖動到另一個框裏</p>
</div>
<div></div>
</body>
<script type="text/javascript">
document.ondragstart=function(e){
e.dataTransfer.setData("text/html",e.target.id);
console.log(e.target.id);
}
document.ondrag=function(e){
console.log("drag");
}
document.ondragend=function(e){
console.log("dragend");
}
document.ondragleave=function(e){
console.log("dragleave");
}
document.ondragover=function(e){
e.preventDefault();
}
document.ondrop=function(e){
var id=e.dataTransfer.getData("text/html"); //只有在ondrop有效
e.target.appendChild(document.getElementById(id));
}
</script>
</html>