今天和大家分享一个jquery实现可以drag(拖拽)效果的实例,不多说了,直接上代码和demo。
HTML代码
<div id="drag"> <div class="title"></div> <div>内容</div> </div>
CSS代码
<style type="text/css"> body,blockquote,button,dl,dd,fieldset,figure,h1,h2,h3,h4,h5,h6,hr,input,ul,ol,p,pre,select,textarea{ margin:0; } button,th,td,fieldset,legend,input,ul,ol,select,textarea{ padding:0; } body{ color:#000; font:12px SimSun, "Microsoft YaHei", Arial, Helvetica, sans-serif; } li{ list-style-type:none; } body{ height:1000em; } #drag{ position:absolute; left:50%; top:50%; width:30em; height:20em; margin:-10em 0 0 -15em; border:1px solid #000000; background-color:yellow; overflow:hidden; } #drag .title{ width:30em; height:2em; background-color:#dddddd; font-size:1em; line-height:2em; text-align:center; cursor:move; } </style>
JS代码
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script> <script type="text/javascript"> (function ($) { $.fn.drag = function (opts) { var $this = $(this), opts = $.extend($.fn.drag.defaults, opts), obj = $this.find("." + opts.dragClassName), // 鼠标按下可拖拽的元素 obj = obj.nodeName ? obj : $this, // hack,拖拽的元素就是自身 disX = 0, disY = 0; /* * * 拖拽功能 * */ obj.on("mousedown", function (event) { var position = $this.position(), $document = $(document); disX = event.pageX - position.left; disY = event.pageY - position.top; event.preventDefault(); // 取消浏览器默认行为,防止,拖拽图片时的bug // 事件捕获,防止拖拽图片或者选中文字时的bug if ($this.setCapture) { $this.setCapture(); } opts.dragDown(); $document.on("mousemove", function (event) { var left = event.pageX - disX, top = event.pageY -disY, rL = opts.rowL - parseInt($this.css("marginLeft")), rR = opts.rowR - $this.outerWidth(true) - parseInt($this.css("marginRight")), cT = opts.colT - parseInt($this.css("marginTop")), cB = opts.colB - $this.outerHeight(true) - parseInt($this.css("marginBottom")); if (!!opts.isBorder) { left = left < rL ? rL : left; left = left > rR ? rR : left; top = top < cT ? cT : top; top = top > cB ? cB : top; } $this.css({ left : left + "px", top : top + "px" }); event.preventDefault(); // 取消浏览器默认行为,防止,拖拽图片时的bug(IE8及以下 必须加在这才行) opts.dragMove(); }); $document.on("mouseup", function (event) { $document.off("mousemove"); $document.off("mouseup"); if ($this.releaseCapture) { $this.releaseCapture(); } opts.dragUp(); }); }); return $this; }; /* * *默认参数 * */ $.fn.drag.defaults = { dragClassName : "title",// 鼠标按下可拖拽的元素的class isBorder : true,// rowL,rowR,colT,colB 只有在isBorder为true时才有效 rowL : 0, rowR : $(window).width(), colT : 0, colB : $(window).height(), dragDown : $.noop,//鼠标按下时的回调函数 dragMove : $.noop,//鼠标移动时的回调函数 dragUp : $.noop//鼠标抬起时的回调函数 }; })(jQuery); /* * * 调用函数 * */ jQuery(function () { $("#drag").drag(); $("#img").drag(); $("#div").drag(); }); </script>