感觉没什么好说的,都在代码里面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>RRHouJiZhe@163.com</title> <style> #app { width: 100%; height: 100%; } .digo { position: absolute; top: 100px; left: 100px; width: 200px; height: 200px; background-color: aquamarine; border-radius: 5px; } .digo .title { position: relative; top: 5px; height: 30px; /* width: 100%; */ background-color: antiquewhite; margin: 0 2px; } </style> </head> <body> <div id="app"> <div class="digo" id="digo"> <div class="title" onmousedown="f1()"></div> </div> </div> <script> // 点击窗口触发 function f1() { var digo = document.getElementById("digo"); var event = event || window.event; // 1.获取鼠标在窗口(当前div)中的位置 var offsetX = event.offsetX var offsetY = event.offsetY let x = offsetX let y = offsetY // 移动触发 document.onmousemove = function() { var event = event || window.event; // 2.获取鼠标在浏览器中的位置 var clientX = event.clientX var clientY = event.clientY // 3.计算相对位置 move(digo, clientX - x, clientY - y) } // 鼠标弹起触发 document.onmouseup = function() { document.onmousemove = null document.onmouseup = null; } } function move(digo, x, y) { // 可视窗口的大小 var winWid = document.documentElement.clientWidth || document.body.clientWidth; var winHei = document.documentElement.clientHeight || document.body.clientHeight; // console.log(winWid + " === " + winHei); // 可视窗口的大小去减掉 所需移动的窗口的大小,就可以的出这个窗口所能达到的最边缘值 winWid = winWid - 10 - digo.offsetWidth winHei = winHei - 10 - digo.offsetHeight if (x <= 0) { x = 10 } if (y <= 0) { y = 10 // = 100 // console.log(event.clientY); } if (x > winWid) { x = winWid } if (y > winHei) { y = winHei } // console.log(x, y); digo.style.top = y + 'px' digo.style.left = x + "px" } </script> </body> </html>