Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
function Drag(ele, target) {
function start(e) {
e = e || window.event;
started = true;
moved = this.target;
initX = parseInt(moved.style.left);
initY = parseInt(moved.style.top);
offsetX = e.clientX;
offsetY = e.clientY;
document.onmousemove = function(event) {
if (started) {
event = event || window.event;
var x = event.clientX - offsetX + initX;
var y = event.clientY - offsetY + initY;
var doc = document.documentElement;
//防止往左右移出,如不需要可去掉if
if (x > 0 && x + moved.offsetWidth < Math.max(doc.scrollWidth, doc.clientWidth))
moved.style.left = x + "px";
//防止上下移出,如不需要可去掉if
if (y > 0 && y + moved.offsetHeight < Math.max(doc.scrollHeight, doc.clientHeight))
moved.style.top = y + "px";
}
};
document.onmouseup = function() {
started = false;
document.onmousemove = null;
}
};
ele.target = target;
ele.onmousedown = start;
}
window.onload = function() {
//用法,第一個參數為要用來拖動的元素,第二個參數為被拖動元素。
new Drag(document.getElementById("head"), document.getElementById("box"));
new Drag(document.getElementById("Div2"), document.getElementById("Div1"));
}
</script>
</head>
<body>
<div id="box" style="border:1px solid #ccc; top:20px; left:20px; background-color:#f0f0f0; width:300px; height:180px; position:absolute;">
<div id="head" style="background-color:#ddd; height:26px; cursor:move;"></div>
</div>
<div id="Div1" style="border:1px solid #ccc; top:150px; left:150px; background-color:#f0f0f0; width:300px; height:180px; position:absolute;">
<div id="Div2" style="background-color:#ddd; height:26px; cursor:move;"></div>
</div>
<div id="status" style="position:absolute; right:10px; top:10px;"></div>
</body>
</html>