<html>
<head>
<meta charset="utf-8" />
<title></title>
<style>*{margin: 0;padding: 0;}</style>
</head>
<body>
<div id="demo" style="position:absolute;width: 100px;height: 100px;background: #ccc;border:solid 1px #ccc;">按住左鍵拖動</div>
</body>
<script>
window.onload = function() {
//用于確定是否是拖拽的對象
var drag;
//鼠標(biāo)位于目標(biāo)元素上的時候距離目標(biāo)元素的位置
var x,y;
//取得元素
var ele = document.getElementById('demo');
//鼠標(biāo)按下去
ele.onmousedown = function(evt) {
//取得事件對象
_event = evt || window.event;
//設(shè)置drag元素
target = _event.target || _event.srcElement;
x = _event.clientX - target.offsetLeft;
y = _event.clientY - target.offsetTop;
drag = target;
}
//鼠標(biāo)移動
document.onmousemove = function(evt) {
//確定鼠標(biāo)是在目標(biāo)元素上按下去后才開始移動
if(drag) {
_event = evt || window.event;
//設(shè)置邊界
var left = _event.clientX - x;
var top = _event.clientY - y;
body = document.documentElement || document.body;
if (left < 0) left = 0;
if (left > body.offsetWidth - drag.offsetWidth) left = body.offsetWidth - drag.offsetWidth;
if (top < 0) top = 0;
if (top > (body.offsetHeight - drag.offsetHeight)) top = (body.offsetHeight - drag.offsetHeight);
//設(shè)置樣式
drag.style.cursor = 'move';
drag.style.border = 'dashed 1px red';
drag.style.left = left + 'px';
drag.style.top = top + 'px';
}
}
//松開鼠標(biāo)
document.onmouseup = function(evt) {
if(drag) {
//卸載樣式
drag.style.cursor = '';
drag.style.border = 'dashed 1px #ccc';
}
drag = null;
}
}
</script>
</html>