无聊时封装的拖动插件 任何浏览器都可用
jQuery.fn.extend({ Drap: function (opts) { var _self = this, _this = $(this), posX = 0, posY = 0; opts = jQuery.extend({ DrapMove: null, IsLimit: false, Callback: function () { } }, opts || {}); _self.mousemove = function (e) { e.stopPropagation(); if ($.browser.msie) { e = window.event; } var x = e.clientX - posX; var y = e.clientY - posY; if (opts.IsLimit) { if (x < 0) { x = 0; } if (y < 0) { y = 0; } if (x > ($(document).width() - _this.width() - 2)) { x = ($(document).width() - _this.width() - 2); } if (y > ($(document).height() - _this.height() - 2)) { y = ($(document).height() - _this.height() - 2); } } _this.css("left", x + "px"); _this.css("top", y + "px"); //_this.find(opts.DrapMove).text("top:" + y + ",left:" + (x + _this.width())) } _this.find(opts.DrapMove).mousedown(function (e) { e.stopPropagation(); if ($.browser.msie) { e = window.event; } posX = e.clientX - parseInt(_this.offset().left); posY = e.clientY - parseInt(_this.offset().top); $(document).mousemove(function (ev) { _self.mousemove(ev); }); }); $(document).mouseup(function () { $(document).unbind("mousemove"); opts.Callback(); }); _this.find(opts.DrapMove).css("cursor", "move"); } });
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Drap演示</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="drap.js" type="text/javascript"></script> <script> $(function () { $("#show").Drap({ DrapMove: "#title", IsLimit: true, Callback: function () { alert("end"); } }); $("#close").click(function () { alert("close"); }); }); </script> </head> <body> <div id="show" style="position: absolute; width: 216px; height: 138px; background-color: skyblue; border: solid 1px blue;"> <div id="title" style="background-color: Blue; height: 20px; color: #fff; font-size: 12px; padding-top: 5px; padding-left: 10px;"> 标题 <i id="close" style="float: right; margin-right: 10px">x</i></div> 内容 </div> </body> </html>
插件用法:$(“弹出窗体ID”).Drap({ DrapMove:拖动对象,IsLimit:是否限制范围,Callback:拖动完成后回调});