美国人有一句常用的俗语—“Re-inventing the Wheel”,从字面上来解释就是“重新发明轮子”。可是轮子早已问世,再要去发明岂非劳而无功?
产品经理发下需求,实施者再到网上搜索代码,也许很快就搜到对应的代码。简单的交互和提交常用的交互,很容易的网上找到相应的代码。一些复杂的交互、定制行比较强的交互,网上找代码就有些困难的。所有复杂交互都是简单交互的组成,所以搜索别人的代码是以学习为主,把别人的基础方法掌握了。拿到需求就不必要到网上搜代码,这样永远也不能提升自己的能力。
业余时间写的一个,简单拖拽框架代码,但比较容易扩展。
源码下载:http://yunpan.cn/QGYBju4vcRxZz
例子:
源码:
1 /** 2 * jQuery拖拽 3 * @author: heshimeng1987@qq.com 4 */ 5 ~function($, window, undefined){ 6 var win = $(window), 7 doc = $(document), 8 9 drag = function(target, options){ return new drag.fn.init(target, options); }; drag.fn = drag.prototype = { init: function(target, options){ var that = this; this.target = $(target); options = options || {}; this.root = options.root ? $(options.root) : this.target; this.min = options.min; this.max = options.max; this.start = options.start; this.move = options.move; this.end = options.end; // this.fixed = options.fixed === undefined ? true : options.fixed; this.startPosition = {}; this.movePosition = {}; var _down = function(e){ that.startPosition = {x: e.clientX-parseInt(that.root.css('left')), y: e.clientY-parseInt(that.root.css('top'))}; that.start&&that.start(that.startPosition); doc.bind('mousemove', _move) .bind('mouseup', _end); return false; }, _move = function(e){ that.movePosition = {x: e.clientX - that.startPosition.x, y: e.clientY - that.startPosition.y}; that.limit(); that.root.css({ left: that.movePosition.x, top: that.movePosition.y }); that.move&&that.move(that.movePosition); return false; }, _end = function(){ doc.unbind('mousemove', _move) .unbind('mouseup', _end); that.end&&that.end(that.movePosition); return false; }; this.target.bind('mousedown',_down); }, /** * 移动的位置限制 */ limit: function(){ if(this.min !== undefined){ this.movePosition = { x: Math.max( this.min.x, this.movePosition.x ), y: Math.max( this.min.y, this.movePosition.y ) }; } if(this.max !== undefined ){ this.movePosition = { x: Math.min( this.max.x, this.movePosition.x ), y: Math.min( this.max.y, this.movePosition.y ) }; } } }; drag.fn.init.prototype = drag.fn; $.drag = drag; }(jQuery, this);
后续将制作一个完善的对话框功能,
当然也可以扩展一些小功能。比如,我工作中编写了一个身高拖拽表单,提供一个效果,这里就不提供源码了:
转载请注明出处:http://www.cnblogs.com/dreamback
如有任何建议或疑问,欢迎留言讨论。
.root{width: 280px;position: absolute;background:#ccc;top:450px;left:100px;font-size: 12px;}
.target{height: 32px;line-height: 32px;margin: 0;background:blue;cursor: move;padding-left: 10px;color:#fff;}
#target1{cursor: move;}
#target3,#target2{margin:0}
例子1.
$.drag('#target1');
例子2.
$.drag('#target2',{ root:'#root2' });
例子3.
最小范围:min:{x:100,y:10}
最大范围:max:{x:900,y:2000}
开始:false
移动:false
结束:false
$.drag('#target3', { root:'#root3', min:{x:100,y:10}, max:{x:900,y:2000}, start: function(pos){ $('#isEnd').html('false'); $('#isStart').html('true, x='+pos.x+', y='+pos.y); }, move: function(pos){ $('#isMove').html('true, x='+pos.x+', y='+pos.y); }, end: function(pos){ $('#isEnd').html('true, x='+pos.x+', y='+pos.y); $('#isStart').html('false'); $('#isMove').html('false'); } });