拖拽插件,可支持多个dom绑定
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script language="javascript" src="jquery-1.9.1.min.js"></script>
<style>
.div1 {
width: 200px;
height: 200px;
background: #000;
position: absolute;
cursor: pointer;
}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div1"></div>
<script>
(function($){
class drag{
constructor(opts){
let that=this;
that.init(opts);
}
init(opts){
let that=this;
$.each(opts.dom,function(i,_i){
that.bind(_i);
})
}
bind(d){
let that =this,
X = 0,
Y = 0;
$(d).on("mousedown", function (ev){
let oEvent = ev || event;
X = oEvent.clientX - d.offsetLeft;
Y = oEvent.clientY - d.offsetTop;
document.onmousemove = function (ev){
let oEvent = ev||event;
d.style.left = that.caclX(d,(oEvent.clientX - X))+ 'px';
d.style.top = that.caclY(d,(oEvent.clientY - Y))+ 'px';
};
document.onmouseup = function (){
document.onmousemove = null;
document.onmouseup = null;
}
});
}
caclX(d,x){
if(x<0) {
x=0;
}else if(x>document.documentElement.clientWidth - d.offsetWidth){
x = document.documentElement.clientWidth - d.offsetWidth;
}
return x;
}
caclY(d,y){
if(y<0) {
y=0;
}else if(y>document.documentElement.clientHeight- d.offsetHeight){
y= document.documentElement.clientHeight - d.offsetHeight;
}
return y;
}
}
$.fn.drag= function(){
var arg = arguments;
arg.dom=this;
new drag(arg);
};
})(jQuery)
$(()=>{
$(".div1").drag();
})
</script>
</body>
</html>