高级拖拽

来源:互联网 发布:广州优享网络 编辑:程序博客网 时间:2024/05/22 01:44
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="button" value = '创建div' id="btn" />
</body>
</html>
<script type="text/javascript">
var oBtn = document.getElementById('btn');
oBtn.onclick = function(){
var dd = new DragDiv(100,100);
dd.createDiv();
}
function DragDiv(w,h){
this.w = w;
this.h = h;
}
//创建div方法
DragDiv.prototype.createDiv = function(){
this.oDiv = document.createElement("div");
this.oDiv.style.width = this.w + "px";
this.oDiv.style.height = this.h + "px";
this.oDiv.style.background ="#"+getColor();
this.oDiv.style.position = "absolute";
this.oDiv.style.left = this.rand(100,window.innerWidth-100) +"px";
this.oDiv.style.top = this.rand(100,window.innerHeight-100) +"px";
document.body.appendChild(this.oDiv);
this.drag();
}
//随机方法
DragDiv.prototype.rand = function(min,max){
return Math.floor(Math.random()*(max-min+1)) + min;
}
//拖拽
DragDiv.prototype.drag = function(){
var that = this;
this.oDiv.onmousedown = function(e){
var e = e || event;
var rex = e.offsetX;
var rey = e.offsetY;
document.onmousemove = function(e){
var e = e || event;
var x = e.clientX - rex;
var y = e.clientY - rey;
var maxL = window.innerWidth - 100;
var maxT = window.innerHeight - 100;
x = x<=0 ? 0 : (x>maxL ? maxL : x);
    y = y<=0 ? 0 : (y>maxT ? maxT : y);
that.oDiv.style.left = x + "px";
that.oDiv.style.top = y + "px";
}
}
document.onmouseup = function(){
document.onmousemove = "";
}
}
function getRand(min,max){
return Math.floor( Math.random()*(max-min+1) + min );
}
function getColor(){
var r = getRand(0,255).toString(16);
var g = getRand(0,255).toString(16);
var b = getRand(0,255).toString(16);
return (r.length<2?"0"+r:r) + (g.length<2?"0"+g:g) + (b.length<2?"0"+b:b) ;
}
</script>
原创粉丝点击