標籤:
作為一個馬上要找工作、非電腦專業、熱愛前端的大四狗,最近開始瘋狂寫demo、看書,準備九、十月份的校招。
晚上用js實現了一個比較簡單(low)的拖拽效果,初步測試相容性還是不錯的,於是寫一段小博文記錄下~大神求輕噴
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Document</title> <style> #box { width: 100px; height: 100px; background: red; position: absolute; } </style></head><body> <div id="box"></div> <script> window.onload = function (){ var disX = 0; var disY = 0; var oBox = document.getElementById("box"); oBox.onmousedown = function (ev){ var oEvent = ev || event; oBox.style.cursor = "move"; disX = oEvent.clientX - oBox.offsetLeft; disY = oEvent.clientY - oBox.offsetTop; document.onmousemove = function (ev){ var oEvent = ev || event; var theLeft = oEvent.clientX - disX; var theTop = oEvent.clientY - disY; // 禁止使用者從瀏覽器左框拖出 if (theLeft < 0) { theLeft = 0; } else if (theLeft > document.documentElement.clientWidth- oBox.offsetWidth) { theLeft = document.documentElement.clientWidth- oBox.offsetWidth; } else if (theTop < 0) { theTop = 0; } else if (theTop > document.documentElement.clientHeight- oBox.offsetHeight) { theTop = document.documentElement.clientHeight- oBox.offsetHeight; } oBox.style.left = theLeft + ‘px‘; oBox.style.top = theTop + ‘px‘; } } document.onmouseup = function (){ document.onmousemove =null; } // 視窗調整大小時的處理方法 window.onresize = function (){ oBox.style.left = document.documentElement.clientWidth/2-oBox.offsetWidth/2 + ‘px‘; oBox.style.top = document.documentElement.clientHeight/2-oBox.offsetHeight/2 + ‘px‘; } // 相容firefox 3.6.19 return false; } </script></body></html>
[javascript]一種相容性比較好的簡單拖拽