<!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>*拖动的DIV层方块</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<script type="text/javascript" src="js/jquery.min.js"></script>
<style type="text/css">
#draggable {
background-color: green;
font-size: 9pt;
padding: 30px;
color: white;
width: 360px;
height: 224px;
position: absolute;
}
</style>
<script type="text/javascript">
var Drager = function () { };
Drager.dom = null;
Drager.selector = null;
Drager.prototype.xdrag = function (dom, selector) {
var obj = this;
obj.selector = selector;
dom.onmousedown = function (e) {
e = obj.getEvent(e);
e.preventDefault && e.preventDefault();
obj.dom = this;
obj.dom.x = e.clientX+$(window).scrollLeft() - obj.dom.offsetLeft;
obj.dom.y = e.clientY + $(window).scrollTop() - obj.dom.offsetTop;
document.onmousemove = function (e) { obj.move(e, obj); };
document.onmouseup = function (e) { obj.end(e, obj); };
};
};
Drager.prototype.getEvent = function (e) {
if (!e) {
e = window.event;
e.target = e.srcElement;
e.layerX = e.offsetX;
e.layerY = e.offsetY;
}
return e;
};
Drager.prototype.move = function (e,srcObj) { e = srcObj.getEvent(e);
var oLeft, oTop;
oLeft = e.clientX + $(window).scrollLeft() - srcObj.dom.x;
oTop = e.clientY + $(window).scrollTop() - srcObj.dom.y; if (srcObj.selector != null) {
if (oLeft > parseInt( srcObj.dom.style.left)) {
if (oLeft + $(srcObj.dom).outerWidth() > $(srcObj.selector).offset().left + $(srcObj.selector).outerWidth()) {
oLeft = $(srcObj.selector).offset().left + $(srcObj.selector).outerWidth() - $(srcObj.dom).outerWidth();
}
} else if (oLeft < parseInt(srcObj.dom.style.left)) {
if (oLeft < $(srcObj.selector).offset().left ) {
oLeft = $(srcObj.selector).offset().left ;
}
}
if (oTop > parseInt(srcObj.dom.style.top)) {
if (oTop + $(srcObj.dom).outerHeight() > $(srcObj.selector).offset().top + $(srcObj.selector).outerHeight()) {
oTop = $(srcObj.selector).offset().top + $(srcObj.selector).outerHeight() - $(srcObj.dom).outerHeight();
}
} else if (oTop < parseInt(srcObj.dom.style.top)) {
if (oTop < $(srcObj.selector).offset().top) {
oTop = $(srcObj.selector).offset().top;
}
}
}
srcObj.dom.style.left = oLeft + 'px';
srcObj.dom.style.top = oTop + 'px';
};
Drager.prototype.end = function (e,srcObj) {
e = srcObj.getEvent(e);
srcObj.dom = document.onmousemove = document.onmouseup = null;
}; var drag = new Drager();
</script>
<script type="text/javascript"> window.onload = function () {
var obj = document.getElementById('draggable');
//第二个参数是限制范围,可不填
drag.xdrag(obj,".container");
} </script>
</head>
<body>
<div class="container" style="width:800px;height:500px; background-color:red;">
<div id="draggable">这个可以拖动!</a></div>
</div> </body>
</html>