原生js实现拖拽(碰撞检测)
程序员文章站
2024-03-15 21:48:24
...
js实现拖拽
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
padding: 0;
margin: 0;
}
#drag1{
position: absolute;
width: 100px;
height: 100px;
background: #ccc;
}
</style>
</head>
<body>
<div id="drag1"></div>
<script>
/* var oDrag =document.getElementById("drag1");
var disX =0;
var disY =0;
oDrag.onmousedown=function(ev){
ev =window.event || ev;
disX =ev.clientX -this.offsetLeft;
disY =ev.clientY -this.offsetTop;
document.onmousemove=function(ev){
ev =window.event || ev;
var cW =document.body.clientWidth || document.documentElement.clientWidth;
var cH =document.body.clientHeight || document.documentElement.clientHeight;
oDrag.style.left = (ev.clientX -disX)+"px";
oDrag.style.top = (ev.clientY -disY)+"px";
if(oDrag.offsetLeft<0){
oDrag.style.left=0+"px"
}
if(oDrag.offsetTop<0){
oDrag.style.top=0+"px"
}
if(oDrag.offsetTop>cH -oDrag.offsetHeight){
oDrag.style.top=cH -oDrag.offsetHeight+"px"
}
if(oDrag.offsetLeft>cW -oDrag.offsetWidth){
oDrag.style.left=cW -oDrag.offsetWidth+"px"
}
}
document.onmouseup=function(){
document.onmousemove =null;
document.onmouseup =null;
}
}*/
function Drag(json){
this.id =document.getElementById(json.id);
this.disX =0;
this.disY =0;
var _this =this;
this.id.onmousedown=function(ev){
ev =window.event || ev;
_this.init(ev);
document.onmousemove=function(ev){
ev =window.event || ev;
_this.fnMove(ev);
}
document.onmouseup=function(){
_this.fnUp();
}
}
}
Drag.prototype.init=function(ev){
this.disX=ev.clientX -this.id.offsetLeft;
this.disY =ev.clientY -this.id.offsetTop;
}
Drag.prototype.fnMove=function(ev){
this.id.style.left = (ev.clientX - this.disX)+"px";
this.id.style.top = (ev.clientY - this.disY)+"px";
var cW =document.body.clientWidth || document.documentElement.clientWidth;
var cH =document.body.clientHeight || document.documentElement.clientHeight;
if(this.id.offsetLeft<=0){
this.id.style.left=0+"px"
}
if(this.id.offsetTop<=0){
this.id.style.top=0+"px"
}
if(this.id.offsetTop>=cH -this.id.offsetHeight){
this.id.style.top=(cH -this.id.offsetHeight)+"px"
}
if(this.id.offsetLeft>=cW -this.id.offsetWidth){
this.id.style.left=(cW -this.id.offsetWidth)+"px"
}
}
Drag.prototype.fnUp=function(ev){
document.onmousemove =null;
document.onmouseup =null;
}
new Drag({
id:"drag1",
bgcolor:""
})
</script>
</body>
</html>