1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>无标题文档</title>
6 <style>
7 *{margin:0;padding:0;}
8 #box{width:10px;height:10px;background:#f00;position:absolute;bottom:0;right:0;}
9 #main{width:200px;height:250px;background:#ccc;position:relative;}
10 .box{border:1px dashed #000;position:absolute;}
11 </style>
12 <script>
13 window.onload=function()
14 {
15 drag('box');
16 };
17 function drag(id)
18 {
19 var obj = document.getElementById(id);
20 var oMain = document.getElementById('main');
21 obj.onmousedown=function(ev)
22 {
23 var ev = ev||event;
24 var disX = ev.clientX - obj.offsetLeft;
25 var disY = ev.clientY - obj.offsetTop;
26 if(obj.setCapture)
27 {
28 obj.onmousemove=fnMove;
29 obj.setCapture();
30 obj.onmouseup=fnUp;
31 }
32 else
33 {
34 document.onmousemove=fnMove;
35 document.onmouseup=fnUp;
36 };
37 function fnMove(ev)
38 {
39 var ev = ev||event;
40 oMain.style.width=ev.clientX - disX+obj.offsetWidth+'px';
41 oMain.style.height=ev.clientY - disY+obj.offsetHeight+'px';
42 if(oMain.offsetLeft<=0)
43 {
44 oMain.style.left=0;
45 }
46 else if(oMain.offsetLeft>=document.documentElement.clientWidth-oMain.offsetWidth)
47 {
48 oMain.style.left=document.documentElement.clientWidth-oMain.offsetWidth+'px';
49 }
50 if(oMain.offsetTop<=0)
51 {
52 oMain.style.top=0;
53 }
54 else if(oMain.offsetTop>=document.documentElement.clientHeight-oMain.offsetHeight)
55 {
56 oMain.style.top=document.documentElement.clientHeight-oMain.offsetHeight;
57 };
58 };
59 function fnUp()
60 {
61 this.onmousemove=null;
62 this.onmouseup = null;
63 if(this.releaseCapture)
64 {
65 this.releaseCapture();
66 };
67
68 };
69 return false;
70 };
71 };
72 </script>
73 </head>
74
75 <body>
76 <div id="main">
77 <div id="box"></div>
78 </div>
79 </body>
80 </html>