html代碼:
javascript
<div id="div1"></div>
css代碼:
css
#div1{width:100px;height:100px;background:red;position:absolute}
javascript代碼:
html
window.onload=function(){ var oDiv=document.getElementById("div1"); var x=0; var y=0; oDiv.onmousedown=function(ev){ var oEvent=ev||event; //鼠標的橫座標減去div的offsetLeft x=oEvent.clientX-oDiv.offsetLeft; //鼠標的縱座標減去div的offsetTop y=oEvent.clientY-oDiv.offsetTop; document.onmousemove=function(ev){ var oEvent=ev||event; var left=oEvent.clientX-x; var right=oEvent.clientY-y; //判斷左邊是否過界 if(left<0){ left=0; } //判斷右邊是否過界 else if(left>document.documentElement.clientWidth-oDiv.offsetWidth){ left=document.documentElement.clientWidth-oDiv.offsetWidth; } //判斷上邊是否過界 if(right<0){ right=0; } //判斷下邊是否過界 else if(right>document.documentElenment.clientHeight){ right=document.documentElenment.clientHeight-oDiv.offsetHeight; } oDiv.style.left=left+"px"; oDiv.style.top=right+"px"; } document.onmouseup=function(){ //清空document的事件 document.onmousemove=null; document.onmouseup=null; } //解決低版本火狐bug,幹掉系統默認 return false; } }