您好,登錄后才能下訂單哦!
本文實例為大家分享了JS實現拖拽效果的具體代碼,供大家參考,具體內容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> #wrap { position: relative; border: 1px solid #000; width: 800px; height: 500px; } #drog { position: absolute; left: 0; top: 0; width: 100px; height: 100px; background: red; cursor: move; } </style> </head> <body> <div id="wrap"> <div id="drog"></div> </div> <script type="text/javascript" src="startmove.js"></script> <script type="text/javascript"> (function(){ var drog = document.querySelector('#drog'); /* 1.記錄按下的時候的鼠標位置 2.記錄按下的時候元素的位置 */ drog.onmousedown = function(e){ var startElY = css(drog,"top"); var startElX = css(drog,"left"); var startMouseX = e.clientX; var startMouseY = e.clientY; /* 求出鼠標移動的距離, 操作元素也移動相應的距離 為了可以一直跟隨,所以添加給document */ document.onmousemove = function(e){ var nowMouseX = e.clientX; var nowMouseY = e.clientY; var disX = nowMouseX - startMouseX; var disY = nowMouseY - startMouseY; var x = disX + startElX; var y = disY + startElY; css(drog,"left",x); css(drog,"top",y); }; document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; }; }; })(); </script> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。