1. 程式人生 > 其它 >JavaScript 滑鼠拖動元素

JavaScript 滑鼠拖動元素

直接上程式碼:

<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge"
> <title>滑鼠拖動</title> </head> <body> <div id="cute" style="position: absolute; width: 266.66px; height: 433.33px; background: url(./cute.png); background-size: 100% 100%;"></div> <script> // 獲取需要拖動的元素 var cute = document.getElementById(
'cute'); // 變數賦初值 var x = y = l = t = 0; var isMove = false; // 滑鼠按住待拖動元素時 cute.onmousedown = function(e) { // 更新滑鼠座標變數 x = e.clientX; y = e.clientY; // 更新元素座標變數 t = cute.offsetTop; l = cute.offsetLeft;
// 修改滑鼠樣式 cute.style.cursor = 'move'; // 開啟拖動開關 isMove = true; } // 滑鼠離開待拖動元素時 cute.onmouseup = function() { // 還原滑鼠樣式 cute.style.cursor = 'default'; // 關閉拖動開關 isMove = false; } // 滑鼠移動時 window.onmousemove = function(e) { // 拖動開關關閉,則不移動元素 if(isMove == false) { return; } // 根據滑鼠偏移量計算新的元素座標 var nl = e.clientX - ( x - l ); var nt = e.clientY - ( y - t ); // 修改元素座標 cute.style.left = nl + 'px'; cute.style.top = nt + 'px'; } </script> </body> </html>

另外分享程式碼中用到的"cute.png",圖源不明,是從同事那要來的:

歡迎轉載,轉載時請註明來源。