html代码:
1 <div id="div1"></div>
css代码:
1 #div1{ 2 width:100px; 3 height:100px; 4 background:red; 5 position:absolute; 6 }
javascript代码:
1 window.onload = function(){ 2 var oDiv = document.getElementById("div1"); 3 4 drag(oDiv); 5 6 function drag(obj){ 7 obj.onmousedown = function(ev){ 8 var ev = ev || event; 9 10 var disX = ev.clientX - this.offsetLeft; 11 var disY = ev.clientY - this.offsetTop; 12 13 if(obj.setCapture){ 14 obj.setCapture(); 15 } 16 17 document.onmousemove = function(ev){ 18 var ev = ev || event; 19 20 var L = ev.clientX - disX; 21 var T = ev.clientY - disY; 22 23 if( L < 100 ){ 24 L = 0; 25 }else if(L>document.documentElement.clientWidth - obj.offsetWidth){ 26 L = document.documentElement.clientWidth - obj.offsetWidth; 27 } 28 29 if( T < 0 ){ 30 T = 0; 31 }else if(T>document.documentElement.clientHeight - obj.offsetHeight){ 32 T = document.documentElement.clientHeight - obj.offsetHeight; 33 } 34 35 obj.style.left = L + "px"; 36 obj.style.top = T + "px"; 37 } 38 39 document.onmouseup = function(){ 40 document.onmousemove = document.onmouseup = null; 41 if(obj.releaseCapture){ 42 obj.releaseCapture(); 43 } 44 } 45 } 46 } 47 }