| - | ---------------------------------------------------------------------- |
| | <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>Document</title> |
| | <style> |
| | * { |
| | margin: 0; |
| | padding: 0; |
| | } |
| | |
| | #box { |
| | height: 100px; |
| | width: 100px; |
| | background-color: red; |
| | position: relative; |
| | } |
| | </style> |
| | </head> |
| | |
| | <body> |
| | <div id="box"></div> |
| | <script src="[./jquery-3.6.0.js](./jquery-3.6.0.js)"></script> |
| | <script> |
| | $('#box').mousedown(function (e) { |
| | //获取鼠标的坐标 |
| | var disX = e.pageX - $('#box').offset().left |
| | var disY = e.pageY - $('#box').offset().top |
| | $(document).mousemove(function (e) { |
| | //鼠标移动的距离 |
| | var l = e.pageX - disX |
| | var t = e.pageY - disY |
| | |
| | //当鼠标移动距离小于0时 |
| | if (l < 0) { |
| | l = 0 |
| | } |
| | //限制最大值 |
| | else if (l > $(document).width() - $('#box').outerWidth()) { |
| | l = $(document).width() - $('#box').outerWidth() |
| | |
| | } |
| | //当鼠标移动距离小于0时 |
| | if (t < 0) { |
| | t = 0 |
| | } |
| | //限制最大值 |
| | else if (t > $(document).height() - $('#box').outerHeight()) { |
| | t = $(document).height() - $('#box').outerHeight() |
| | } |
| | //修改定位 |
| | $('#box').css({ |
| | left: l + 'px', |
| | top: t + 'px' |
| | }) |
| | }) |
| | |
| | $(document).mouseup(function () { |
| | //移除document上的所有事件 |
| | $(document).off() |
| | }) |
| | |
| | }) |
| | |
| | </script> |
| | </body> |
| | |
| | </html>