这几天看了一点和event相关的东西,然后就尝试写了一个简单的拖拽,并封装为函数drop(bar,target)
<!doctype html>
<head>
<meta charset="utf-8">
<style>
*{margin:0;padding:0;}
#odiv{height:200px;width:300px;background-color:red;position:absolute;left:400px;top:300px;}
#son{height:30px;width:300px;background-color:pink;cursor:pointer;}
</style>
</head>
<body>
<div id="odiv">
<div id="son">
</div>
</div>
<script>
function drop(bar,target){
bar.onmousedown=drag;
function drag(event){
event=event||window.event;
var ox=event.clientX-target.offsetLeft,oy=event.clientY-target.offsetTop;
document.onmousemove=function(event){
event=event||window.event;
var oh=document.documentElement.clientHeight,ow=document.documentElement.clientWidth,
maxy=oh-target.offsetHeight,maxx=ow-target.offsetWidth;
var x=event.clientX-ox,y=event.clientY-oy;
if(x<0)x=0;
else if(x>maxx)x=maxx;
if(y<0)y=0;
else if(y>maxy)y=maxy;
target.style.left=x+"px";
target.style.top=y+"px";
};
document.onmouseup=function(){
document.onmousemove=null;
document.onmouseup=null;
};
}}
var target=document.getElementById("odiv"),bar=document.getElementById("son");
drop(bar,target);
</script>
</body>
</html>