您好,登錄后才能下訂單哦!
本文實例為大家分享了JS+DIV實現拖動效果的具體代碼,供大家參考,具體內容如下
效果圖
思路
代碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="main" > <div id="title" ></div> <div class="box"></div> </div> <script> var startx; var starty; var startLeft; var startTop; var titleDiv=document.getElementById("title"); var mainDiv=document.getElementById("main"); var isDown=false; // 鼠標按下 function movedown(e){ e=e?e:window.event; isDown=true; startx=e.clientX; starty=e.clientY; startLeft=parseInt(mainDiv.style.left); startTop=parseInt(mainDiv.style.top); } // 鼠標移動 function move(e){ e=e?e:window.event; if(isDown) { mainDiv.style.left = e.clientX - (startx - startLeft)+"px"; mainDiv.style.top = e.clientY - (starty - startTop)+"px"; } } // 鼠標松開 function moveup(){ isDown=false; } titleDiv.οnmοusedοwn=movedown; titleDiv.οnmοusemοve=move; titleDiv.οnmοuseup=moveup; </script> </body> </html>
優化(封裝,以及解決拖動問題(事件捕獲))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div id="main" > <div id="title" ></div> <div class="box"></div> </div> <script> function Mover(title) { this.obj = title; this.startx = 0; this.starty; this.startLeft; this.startTop; this.mainDiv = title.parentNode; var that = this; this.isDown = false; this.movedown = function (e) { e = e ? e : window.event; if (!window.captureEvents) { this.setCapture(); } //事件捕獲僅支持ie // 函數功能:該函數在屬于當前線程的指定窗口里設置鼠標捕獲。一旦窗口捕獲了鼠標, // 所有鼠標輸入都針對該窗口,無論光標是否在窗口的邊界內。同一時刻只能有一個窗口捕獲鼠標。 // 如果鼠標光標在另一個線程創建的窗口上,只有當鼠標鍵按下時系統才將鼠標輸入指向指定的窗口。 // 非ie瀏覽器 需要在document上設置事件 that.isDown = true; that.startx = e.clientX; that.starty = e.clientY; that.startLeft = parseInt(that.mainDiv.style.left); that.startTop = parseInt(that.mainDiv.style.top); } this.move = function (e) { e = e ? e : window.event; if (that.isDown) { that.mainDiv.style.left = e.clientX - (that.startx - that.startLeft) + "px"; that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px"; } } this.moveup = function () { that.isDown = false; if (!window.captureEvents) { this.releaseCapture(); } //事件捕獲僅支持ie } this.obj.onmousedown = this.movedown; this.obj.onmousemove = this.move; this.obj.onmouseup = this.moveup; //非ie瀏覽器 document.addEventListener("mousemove", this.move, true); } var mover = new Mover(document.getElementById("title")); //寫兩個是為了解決 ie 和非ie 瀏覽器關于事件捕獲 的兼容性問題 </script> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。