<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>简单拖拽实现</title>
<style type="text/css">
*{margin:0;padding:0;}
#box{ margin:20px auto; position:relative; width:400px; height:400px; background:#ccc; border:1px solid #333; postion:relative; }
#dragBox{ width:50px; height:50px; text-align:center; line-height: 50px;position: absolute; background:blue; cursor:move; font-size:12px; color:#fff;}
</style>
</head>
<body>
<div id="box">
<div id="dragBox">拖我</div>
</div>
<script type="text/javascript">
var
VVG = {};
VVG.DOM = {
$:
function
(id) {
return
typeof id == "string" ? document.getElementById(id) : id;
},
bindEvent:
function
(node, type, func) {
if
(node.addEventListener) {
node.addEventListener(type, func, false);
}
else
if
(node.attachEvent) {
node.attachEvent("on" + type, func);
}
else
{
node["on" + type] = func;
}
},
getEvent:
function
(event) {
return
event ? event : window.event;
},
getTarget:
function
(event) {
return
event.target || event.srcElement;
}
}
var
DragDrop =
function
() {
var
box = VVG.DOM.$("box");
var
dragBox = VVG.DOM.$("dragBox");
var
dragging = null;
function
drag(event) {
event = VVG.DOM.getEvent(event);
var
target = VVG.DOM.getTarget(event);
switch
(event.type) {
case
"mousedown":
if
(target.id == "dragBox"){
dragging = target;
}
break
;
case
"mousemove":
if
(dragging){
sTop = document.documentElement.scrollTop || document.body.scrollTop;
dragging.style.left = (event.clientX - box.offsetLeft - dragBox.offsetWidth/2) + "px";
dragging.style.top = (event.clientY + sTop - box.offsetTop - dragBox.offsetHeight/2 ) + "px";
var
left = parseInt(dragging.style.left);
var
top = parseInt(dragging.style.top);
if
(left < 0){
dragging.style.left = 0 +"px";
}
if
(top < 0){
dragging.style.top = 0+"px";
}
if
(left > box.offsetWidth - dragBox.offsetWidth){
dragging.style.left = (box.offsetWidth - dragBox.offsetWidth - 2 )+"px";
}
if
(top > box.offsetHeight - dragBox.offsetHeight){
dragging.style.top =( box.offsetHeight - dragBox.offsetHeight - 2 )+"px";
}
}
break
;
case
"mouseup":
dragging = null;
break
;
}
};
return
{
dragStart:
function
() {
VVG.DOM.bindEvent(document, "mousedown", drag);
VVG.DOM.bindEvent(document, "mousemove", drag);
VVG.DOM.bindEvent(document, "mouseup", drag);
}
}
}();
DragDrop.dragStart();
</script>
</body>
</html>