日期:2014-05-16 浏览次数:20427 次
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#draggable {
width:100px;
height:100px;
position:absolute;
top:50px;
left:350px;
background-color:red;
}
</style>
</head>
<body>
<div id='draggable'>draggable</div>
<script>
var data={};
function draggable(e){
var el = e.target;
data = {
startLeft: el.offsetLeft,
startTop: el.offsetTop,
left: el.offsetLeft,
top: el.offsetTop,
startX: e.pageX,
startY: e.pageY,
eTarget:el
}
document.addEventListener('mousedown',doDown);
document.addEventListener('mousemove',doMove);
document.addEventListener('mouseup',doUp);
}
function drag(e){
var d = data;
var l=d.startLeft + e.pageX - d.startX;
var t = d.startTop + e.pageY - d.startY;
data.left = l;
data.top=t;
}
function applyDrag(){
var d = data;
d.eTarget.style.left = d.left + 'px';
d.eTarget.style.top=d.top + 'px';
}
function doDown(e){
drag(e);
applyDrag();
return false;
}
function doMove(e){
drag(e);
applyDrag();
return false;
}
function doUp(e){
drag(e);
applyDrag();
document.removeEventListener('mousedown',doDown);
document.removeEventListener('mousemove',doMove);
document.removeEventListener('mouseup',doUp);
}
var $a = document.getElementById('draggable');
$a.addEventListener('mousedown',draggable);
</script>
</body>
</html>