1、css代碼
#big { border: 1px solid #FF3300; width: 300px; height: 300px; position: relative; } #small { background: #99CC00; width: 50px; height: 50px; position: absolute; cursor: pointer; }
2、JavaScript代碼
<script language="javascript"> function small_down(e) { var obig = document.getElementById("big"); var osmall = document.getElementById("small"); var e = e || window.event; /*用於保存小的div拖拽前的坐標*/ osmall.startX = e.clientX - osmall.offsetLeft; osmall.startY = e.clientY - osmall.offsetTop; /*鼠標的移動事件*/ document.onmousemove = function(e) { var e = e || window.event; osmall.style.left = e.clientX - osmall.startX + "px"; osmall.style.top = e.clientY - osmall.startY + "px"; /*對於大的DIV四個邊界的判斷*/ if (e.clientX - osmall.startX <= 0) { osmall.style.left = 0 + "px"; } if (e.clientY - osmall.startY <= 0) { osmall.style.top = 0 + "px"; } if (e.clientX - osmall.startX >= 250) { osmall.style.left = 250 + "px"; } if (e.clientY - osmall.startY >= 250) { osmall.style.top = 250 + "px"; } }; /*鼠標的抬起事件,終止拖動*/ document.onmouseup = function() { document.onmousemove = null; document.onmouseup = null; }; } </script>
3、html代碼
<body> <div id="big"> <div id="small" onmousedown="small_down(event)"></div> </div> </body>
---恢復內容結束---