让小盒子在大盒子中拖动,不能超出大盒子,如下图:
<!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>Document</title> <style> * { margin: 0; padding: 0; } .bigBox { position: relative; 500px; height: 500px; border: 1px solid #000; margin: 50px auto; } .box { position: absolute; left: 0; top: 0; 100px; height: 100px; background: red; } </style> </head> <body> <div class="bigBox"> <div class="box"></div> </div> <script> var $bigBox = document.querySelector('.bigBox'); var $box = document.querySelector('.box') // 鼠标按下 $box.onmousedown = function (e) { e = e || window.event; // 获取最大移动距离 var maxX = $bigBox.clientWidth - $box.offsetWidth, maxY = $bigBox.clientHeight - $box.offsetHeight; // 获取鼠标偏移量 var x = e.offsetX, y = e.offsetY; // 获取大盒子的偏移量 var left = $bigBox.offsetLeft, top = $bigBox.offsetTop; document.onmousemove = function (e) { e = e || window.event; // 小盒子的移动距离 var moveX = e.pageX - x - left, moveY = e.pageY - y - top; if (moveX < 0) { moveX = 0; } else if (moveX > maxX) { moveX = maxX; } if (moveY < 0) { moveY = 0; } else if (moveY > maxY) { moveY = maxY; } $box.style.left = moveX + 'px'; $box.style.top = moveY + 'px'; } } // 鼠标抬起 document.onmouseup = function () { // 取消时间 document.onmousemove = null; } </script> </body> </html>