jQuery拖拽小插件
基本实现思路是利用了onmousedown,onmouseup,onmousemove三种事件和css中的绝对定位
插件功能:
1.设置拖拽热点
2.设置被拖拽对象
3.设置拖拽范围
默认情况下,拖拽热点和被拖拽对象是同一个元素,拖拽范围是文档窗口
jQuery代码
(function($){ $.fn.drag=function(opts){ var defaults={ dragObj:$(this), scope:{ left:0, top:0, right:$(document).width(), bottom:$(document).height() } } var config=$.extend(defaults,opts); var ifMouseDown=false; var offleft; var offtop; function getPosition(element){ return element.offset(); } function mousedownHandler(event){ var x=event.pageX; var y=event.pageY; offleft=x-getPosition(config.dragObj).left; offtop=y-getPosition(config.dragObj).top; ifMouseDown=true; } function mousemoveHandler(event){ if(ifMouseDown){ $(this).css({"cursor":"move"}) ; var x=event.pageX; var y=event.pageY; var left=x-offleft; var top=y-offtop; if( left>config.scope.left&&left+config.dragObj.width()<config.scope.right){ config.dragObj.css({"left":left+"px"}) } if(top>config.scope.top&&top+config.dragObj.height()<config.scope.bottom){ config.dragObj.css({"top":top+"px"}) } } } $(this).bind("mousedown",mousedownHandler); $(document).bind("mousemove",mousemoveHandler); $(document).bind("mouseup",function(){ ifMouseDown=false;}); } })(jQuery);