<style type="text/css">
#box{
width:100px;
height:100px;
background:red;
position:absolute;
}
#box1{
width:100px;
height:100px;
background:blue;
left:200px;
position:absolute;
}
</style>
<div id="box"></div>
<div id="box1"></div>
<script type="text/javascript">
new Drg('box');
new Drg1('box1');
function Drg(id){
this.ele = document.getElementById(id);
this.ele.onmousedown = function(evt){
this.fndown(evt);
}.bind(this);
}
Drg.prototype.fndown = function(evt){
var evt = evt || window.event;
this.disX = evt.offsetX;
this.disY = evt.offsetY;
document.onmousemove = function(evt){
this.fnmove(evt);
}.bind(this);
document.onmouseup = function(){
this.fnup();
}.bind(this);
document.ondragstart = function(){
return false;
}
}
Drg.prototype.fnmove = function(evt){
var evt = evt || window.event;
this.ele.style.left = evt.pageX - this.disX + 'px';
this.ele.style.top = evt.pageY - this.disY + 'px';
}
Drg.prototype.fnup = function(){
document.onmousemove = document.onmouseup = null;
}
//继承Drg的属性,并给Drg1设置拖拽边界
function Drg1(id){
Drg1.prototype = new Drg(id);
}
Drg1.prototype.fnmove = function(evt){
var evt = evt || window.event;
var left = evt.pageX - this.disX;
var top = evt.pageY - this.disY;
if(left <= 0){
left = 0;
}else if(left >= document.documentElement.clientWidth - this.ele.offsetWidth){
left = document.documentElement.clientWidth - this.ele.offsetWidth;
}
if(top <= 0 ){
top = 0;
}else if(top >= document.documentElement.clientHeight - this.ele.offsetHeight){
top = document.documentElement.clientHeight - this.ele.offsetHeight;
}
this.ele.style.left = left + 'px';
this.ele.style.top = top + 'px';
}
</script>