1.利用js实现
//获取当前鼠标在页面上的坐标
function getPointerPositionInDocument(eventObject) {
var x = eventObject.pageX;
var y = eventObject.pageY;
return {
‘x‘: x,
‘y‘: y
};
}
//获取元素在页面上的位置
function getDimensions(element){
return {
‘left‘:element.offsetLeft,
‘top‘:element.offsetTop,
‘width‘:element.offsetWidth,
‘height‘:element.offsetHeight
};
}
2.利用HTML5+JS
新增属性:draggable
新增事件:ondragstart(拖动开始) ondrag(拖动中) ondragend(拖动结束)
ondragenter(进入投放去区) ondragover(投放去移动) ondragleave(离开投放区) ondrop(投放区投放)
HTML部分:
<div id="dropBlock"></div>
<div id="moveBlock" draggable="true"></div>
JS部分:
(function(){
var dropBlock = document.getElementById("dropBlock");
var moveBlock = document.getElementById("moveBlock");
var moveBlockInitPos = 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(e){
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";
//阻止事件冒泡
e.stopPropagation();
}
document.ondragover = function(e){
var e = getEventObject(e);
//阻止默认事件发生
e.preventDefault();
}
document.ondrop = function(e){
var e = getEventObject(e);
console.log("进入文档投放区");
moveBlock.style.left = moveBlockInitPos.left+"px";
moveBlock.style.top = moveBlockInitPos.top +"px";
}
}())
原文:http://www.cnblogs.com/yttbbd/p/4805610.html