在线演示:http://sandbox.runjs.cn/show/2drrwkrx
关键点:保持一个不变,鼠标拖动时与边框的距离 === 鼠标左击时与边框的距离
源码:
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>具备吸附功能的拖曳</title> <link rel="stylesheet" type="text/css" href="http://sandbox.runjs.cn/uploads/rs/294/c4c2o6mh/base.css"> <style> .c-box{ position: absolute; top:100px; 100px; height: 100px; cursor: move; background-color: #9AFF9A; } </style> <script src="http://sandbox.runjs.cn/uploads/rs/294/c4c2o6mh/jquery.js"></script> </head> <body> <div id="box" class="c-box"></div> <script> var box = $('#box'); //鼠标按下 box.mousedown(function(event) { if(event.which==1){ //左击 var left = box.offset().left,//在当前视口的偏移,可以理解为到最终父级(body,html)的距离,别受到js定位父级 //offsetparent的影响,与其对应的是jQuery中position()方法 top = box.offset().top, d_x = event.pageX - left, d_y = event.pageY - top, wx = $(document).outerWidth(),//浏览器可视区域 wy = $(document).outerHeight(), bx = box.width(), by = box.height(); $(document).mousemove(function(event) { //绑定到doucument,防止移动太快脱离鼠标 var x = event.pageX - d_x, y = event.pageY - d_y; if(x<40) x = 0; else if(wx-x-bx<40) x = wx - bx; if(y<40) y = 0; else if(wy-y-by<40) y = wy-by; box.css({ left: x, top: y }); }); $(document).mouseup(function(event) { $(document).off('mousemove'); }); return false;//防止冒泡 } }); </script> </body> </html>
遇到的问题
(1)window中的top对象,参考资料:http://blog.163.com/zhaoyanping_1125/blog/static/201329153201206105031895/
(2)防止鼠标脱离文本框,讲mouseup,mouseover绑定到doucuemnt
(3)区分offset()方法与position()方法
(4)可以将拖曳封装为通用方法
资料:判断鼠标左击与右击