<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>鼠標拖拽</title>
<script type="text/javascript">
function Drag(o, e){
var e = window.event || e;
var _x = e.offsetX || e.layerX;
var _y = e.offsetY || e.layerY;
o.style.filter = 'Alpha(opacity=70)';
o.style.opacity = '0.7';
document.onmousemove = function(e){
var e = window.event || e;
alert(_x + ", " + _y + "\r\n" + e.clientX + ", " + e.clientY + "\r\n" + e.offsetX + ", " + e.offsetY);
o.style.left = e.clientX - _x + 'px';
o.style.top = e.clientY - _y + 'px';
o.style.cursor="move";
}
document.onmouseup = function(e){
document.onmousemove = null;
o.style.filter = o.style.opacity = '';
o.style.cursor="default";
}
}
</script>
</head>
<body>
<div οnmοusedοwn="Drag(this, event)"
style="position: absolute; border: 1px solid red; background: pink; width: 400px; height: 300px;"></div>
</body>
</html>
綠色字體處: _x, _y已經形成閉包, 是不會變的, 值爲最初始鼠標相對其DIV原點(0,0)的距離
藍色字體處: e.clientX, e.clientY爲鼠標相對屏幕的原點(0,0)的距離
粉色字體處: document.onmouseup和document.onmousemove這兩個事件被設定在drag事件中才產生,這樣的好處是在其他情況下不會產生拖放的效果
紅色字體處: document.onmousemove在onmouseup事件中清除是爲了善後工作, 這點要注意