拖拽:
draggable="true"页面上就能实现拖拽
事件:
ondragstart 拖拽开始事件
ondrag 拖拽中
ondragend 拖拽结束事件
投放区事件:
ondragenter 进入投放区
ondragover 投放区移动
ondragleave 离开投放区
ondrop 投放区投放
例文:
<head>
<meta charset="UTF-8">
<title></title>
<style>
#dropBlock{
width:300px;
height:300px;
position: absolute;
left:0;
top:0;
background: black;
}
#moveBlock{
width: 100px;
height:100px;
position: absolute;
background: red;
left:0;
top:300px;
}
</style>
</head>
<body>
<div id="dropBlock"></div>
<div id="moveBlock" draggable="true"></div>
</body>
<script src="js/drag.js"></script>
<script>
(function(){
var dropBlock = document.getElementById("dropBlock");
var moveBlock = document.getElementById("moveBlock");
var moveBlockInisPos = getDimensions(moveBlock);
var startPoint;
var moveBlockPos;
moveBlock.ondragstart = function(){
var e = getEventObject(e);
//获取鼠标点击时的坐标
startPoint = getPointerPositionInDocument(e)
//获取移动块的位置
moveBlockPos = getDimensions(moveBlock);
}
// moveBlock.ondrag = function(){
// console.log("拖拽中");
// }
// moveBlock.ondragend = function(){
// console.log("拖拽结束");
// }
// dropBlock.ondragenter = function(){
// console.log("进入投放区");
// }
dropBlock.ondragover = function(e){
console.log("投放区移动");
//阻止默认事件发生
e.preventDefault();
}
// dropBlock.ondragleave = function(){
// console.log("离开投放区");
// };
dropBlock.ondrop = function(){
var e = getEventObject(e);
var newPoint = getPointerPositionInDocument(e);
var distance = getPointerDistance(startPoint,newPoint);
moveBlock.style.left = (moveBlockPos.left + distance.x)+"px";
moveBlock.style.top = (moveBlockPos.top + distance.y)+"px";
}
dropBlock.ondragleave = function(){
console.log("离开投放区");
var e=getEventObject(e);
moveBlock.style.left = moveBlockInisPos.left + "px";
moveBlock.style.top = moveBlockInisPos.top + "px";
};
}())
</script>