JS實現滑鼠按下拖拽效果
阿新 • • 發佈:2020-07-24
原生JS實現滑鼠按下拖拽效果,供大家參考,具體內容如下
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>滑鼠拖動</title> <style type="text/css"> body { margin: 0; } div { width: 200px; height: 200px; position: absolute; background-color: pink; } </style> </head> <body> <div onmousedown="downDiv(this)" onmousemove="moveDiv(this)" onmouseup="upDiv(this)"> </div> <script> //定義變數儲存div的寬高 var obj_w,obj_h; //定義一個變數判斷是否執行移動函式 var mouseDown = false; //滑鼠按下函式 function downDiv(obj) { //獲取div的寬高 obj_w = obj.offsetWidth; obj_h = obj.offsetHeight; //滑鼠 var e = event || window.event; //e.clientX/Y 是獲取滑鼠相對瀏覽器的位置;將div中心自動居中到滑鼠 obj.style.left = (e.clientX - obj_w / 2) + "px"; obj.style.top = (e.clientY - obj_h / 2) + "px"; console.log(obj.style.left,obj.style.top) //按下時為ture,鬆開時為false,以判斷是否執行執行mouveDiv mouseDown = true; } //滑鼠移動函式 function moveDiv(obj) { obj_w = obj.offsetWidth; obj_h = obj.offsetHeight; var e = event || window.event; console.log(e.clientX,e.clientY); console.log(obj_w,obj_h); if (mouseDown) { obj.style.left = (e.clientX - obj_w / 2) + "px"; obj.style.top = (e.clientY - obj_h / 2) + "px"; console.log(obj.style.left,obj.style.top) } } //滑鼠鬆開函式 function upDiv(obj) { mouseDown = false; } </script> </body> </html>
更多精彩文章請點選專題: Javascript拖拽特效彙總
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。