jQuery插件之拖拽功能
$.fn.getCss=function(key) { var v = parseInt(this.css(key)); if (isNaN(v)) return false; return v; } $.fn.EasyDrag = function(opts) { opts = $.extend({ handler: null, //divHandler,即为移动区的句柄 onMove: function() { return false; }, onDrop: function() { return false; }, opacity: 0.7 }, opts || {}); var fndragData = { drag: function(e) { var dragData = e.data.dragData; dragData.target.css({ left: dragData.left + e.pageX - dragData.offLeft, top: dragData.top + e.pageY - dragData.offTop }); //移动div的实质是 鼠标move的点的x y 坐标 减去 鼠标down的点的xy左边,然后用目标div(或者其他容器)的left或者top加上这个坐标即可 dragData.handler.css({ cursor: 'move' }); dragData.onMove(e); }, drop: function(e) { var dragData = e.data.dragData; dragData.target.css(dragData.oldCss); //.css({ 'opacity': '' }); dragData.handler.css('cursor', dragData.oldCss.cursor); dragData.onDrop(e); $().unbind('mousemove', fndragData.drag) .unbind('mouseup', fndragData.drop).bind('selectstart', function() { return true; }); } }; return this.each(function() { var divhandler = null; var divmain = $(this); if (opts.handler == null || opts.handler == undefined) divhandler = $(this); else divhandler = $(opts.handler, this).length == 1 ? $(opts.handler, this) : $(this); divhandler.bind("mousedown", function(event) { var oldCss = {}; if (divmain.css('position') != 'absolute') { var e = { mouseClient: { x: event.clientX, y: event.clientY }, me: { h: divmain.position().top, w: divmain.position().left } }; divmain.css('position', 'absolute'); //alert(divmain.css("left")); try { divmain.css({ "left": e.me.w, "top": e.me.h }); } catch (ex) { } } oldCss.cursor = divmain.css('cursor') || 'default'; oldCss.opacity = 1; var dragData = { left: oldCss.left || divmain.getCss('left') || 0, //移动之前目标容器的left top: oldCss.top || divmain.getCss('top') || 0, //移动之前目标容器的top width: divmain.width() || divmain.getCss('width'), height: divmain.height() || divmain.getCss('height'), offLeft: event.pageX, //鼠标down的x(距离浏览器左边, 和 clientX 差不多) offTop: event.pageY, //鼠标down的y(浏览器右边, 和 clientY差不多) oldCss: oldCss, onMove: opts.onMove, onDrop: opts.onDrop, handler: divhandler, target: divmain } divmain.css('opacity', opts.opacity); $().bind('mousemove', { dragData: dragData }, fndragData.drag) .bind('mouseup', { dragData: dragData }, fndragData.drop).bind('selectstart', function() { return false; }); ; }); }); } $(document).ready(function() { $(".dragDiv").EasyDrag({ handler: ".handler" }); });
本人在长沙, 有工作可以加我QQ4658276