jQuery实现拖拽元素
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> div { width: 200px; height: 200px; background-color: red; position: absolute; cursor: move; } * { margin: 0; padding: 0; } </style> </head> <body> <div>dsgsad</div> <div>dsgsad</div> <div>dsgsad</div> <div>dsgsad</div> </body> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $('div').on('mousedown', function(e) { //鼠标按下 $(document).on('mousemove', (e) => {//鼠标移动 let left = e.clientX - $(this).width() / 2//计算元素left值 let top = e.clientY - $(this).height() / 2//计算元素top值 top = suan(top, 0, $(document).innerHeight() - $(this).height())//调用封装的方法 left = suan(left, 0,$(document).innerWidth() - $(this).width())//调用封装的方法 $(this).css({ //给盒子设置坐标 left, top }) e.preventDefault(); }) $(document).on('mouseup', (e) => {//鼠标抬起 $(document).off('mousemove')//移除鼠标移动事件 }) }) function suan(o, min, max) { //重复封装 o < min ? o = min : o > max ? o = max : ''//限制出界 return o } </script> </html>