var ChildDiv = $("#cid"); var width = 0; //鼠標點擊子div的地方和子div的左邊邊距距離 var height = 0; //鼠標點擊子div的地方和子div的上邊邊距距離 ChildDiv.onmousedown = function (ev) //鼠標按下DIV { var ChildDivEvent = ev || event; //捕獲點擊的對象 width = ChildDivEvent.clientX - ChildDiv.offsetLeft; height = ChildDivEvent.clientY - ChildDiv.offsetTop; document.onmousemove = function (ev) //鼠標移動 { var ChildDivEvent = ev || event; var x = ChildDivEvent.clientX - width; var y = ChildDivEvent.clientY - height; if (x < 0) //當DIV的Left小於0,也就是移出左邊 { x = 0; //就把DIV的Left設置為0,就不能移出左邊 } else if (x > $("#pid").width() - ChildDiv.offsetWidth) //DIV不能移出父DIV的右邊 { x = $("#pid").width() - ChildDiv.offsetWidth; } if (y < 0) //上邊 { y = 0; } else if (y > $("#pid").height() - ChildDiv.offsetHeight) //下邊 { y = $("#pid").height() - ChildDiv.offsetHeight; } ChildDiv.style.left = x + 'px'; //DIV的Left設置為新鼠標X坐標減去width的值 ChildDiv.style.top = y + 'px'; //DIV的Top設置為新鼠標Y坐標減去height的值 }; document.onmouseup = function () //鼠標松開時 { document.onmousemove = null; //把鼠標移動清除 document.onmouseup = null; //把鼠標松開清除 }; return false; };