js實現(xiàn)鼠標拖動功能
更新時間:2017年03月20日 11:58:26 作者:18301695170
本文主要介紹了js實現(xiàn)鼠標拖動功能的實例代碼。具有很好的參考價值。下面跟著小編一起來看下吧
效果圖:
代碼如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #div{ width: 200px; height: 200px; background: green; position: absolute; } #div2{ width: 200px; height: 200px; background: gold; position: absolute; top: 200px; left: 200px; } </style> </head> <body> <div id="div"> </div> <div id="div2"></div> <script> window.onload=function(){ var div=document.getElementById("div"); div.onmousedown=function(ev){ var e=window.event || ev; //var Mydiv=document.getElementById("div"); //獲取到鼠標點擊的位置距離div左側(cè)和頂部邊框的距離; var oX=e.clientX-div.offsetLeft; var oY=e.clientY-div.offsetTop; //當鼠標移動,把鼠標的偏移量付給div document.onmousemove=function(ev){ //計算出鼠標在XY方向上移動的偏移量,把這個偏移量加給DIV的左邊距和上邊距,div就會跟著移動 var e=window.event|| ev; div.style.left=e.clientX-oX+"px"; div.style.top=e.clientY-oY+"px"; } //當鼠標按鍵抬起,清除移動事件 document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; } } var div2=document.getElementById("div2"); div2.onmousedown=function(ev){ var e=window.event || ev; //var Mydiv=document.getElementById("div"); //獲取到鼠標點擊的位置距離div左側(cè)和頂部邊框的距離; var oX=e.clientX-div2.offsetLeft; var oY=e.clientY-div2.offsetTop; //當鼠標移動,把鼠標的偏移量付給div document.onmousemove=function(ev){ //計算出鼠標在XY方向上移動的偏移量,把這個偏移量加給DIV的左邊距和上邊距,div就會跟著移動 var e=window.event|| ev; div2.style.left=e.clientX-oX+"px"; div2.style.top=e.clientY-oY+"px"; } //當鼠標按鍵抬起,清除移動事件 document.onmouseup=function(){ document.onmousemove=null; document.onmouseup=null; } } } </script> </body> </html>
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持腳本之家!
相關(guān)文章
詳解如何在Javascript中使用Object.freeze()
這篇文章主要介紹了詳解如何在Javascript中使用Object.freeze(),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-10-10刷新頁面實現(xiàn)方式總結(jié)(HTML,ASP,JS)
多種方法實現(xiàn)頁面的刷新代碼2008-11-11javascript設(shè)置連續(xù)兩次點擊按鈕時間間隔的方法
這篇文章主要介紹了javascript設(shè)置連續(xù)兩次點擊按鈕時間間隔的方法,是非常實用的技巧,需要的朋友可以參考下2014-10-10layui實現(xiàn)數(shù)據(jù)表格table分頁功能(ajax異步)
這篇文章主要為大家詳細介紹了layui實現(xiàn)數(shù)據(jù)表格table分頁功能、異步加載,表格渲染,含條件查詢,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07