css:
<style type="text/css">
.box{
position:absolute;
top:0;
background:#fff000;
width:100px;
height:100px;
}
.left{
left:0px;
}
.right{
right:0;
}
</style>
html:
<div class="box left" id="div1">左边</div>
<div class="box right" id="div2">右边</div>
js:
class Divdrag{
constructor(div){
this.oDiv = document.querySelector(div);
this.oDivX = 0;
this.oDivY = 0;
this.init();
}
init(){
this.oDiv.onmousedown = function(ev){
this.oDivX = ev.clientX - this.oDiv.offsetLeft;
this.oDivY = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = this.fnmove.bind(this);
document.onmouseup = this.fnup.bind(this);
return false;
}.bind(this)
}
fnmove(ev){
this.oDiv.style.left = ev.clientX - this.oDivX + 'px';
this.oDiv.style.top = ev.clientY - this.oDivY + 'px';
if( ev.clientX - this.oDivX <= 0 ){
this.oDiv.style.left = 0 + 'px';
}
if( ev.clientY - this.oDivY <= 0 ){
this.oDiv.style.top = 0 + 'px';
}
if( window.innerWidth - this.oDiv.offsetWidth < ev.clientX - this.oDivX){
this.oDiv.style.left = window.innerWidth - this.oDiv.offsetWidth+ 'px';
}
if( window.innerHeight - this.oDiv.offsetHeight < ev.clientY - this.oDivY){
this.oDiv.style.top = window.innerHeight - this.oDiv.offsetHeight+ 'px';
}
}
fnup(){
document.onmousemove = null;
document.onmouseup = null;
}
}
class sonDrag extends Divdrag{
constructor(div){
super(div);
}
}
new Divdrag("#div1");
var sondrag = new sonDrag("#div2");