请选择 进入手机版 | 继续访问电脑版
查看: 490|回复: 0

[JavaScript/JQuery] jquery拖动小插件

3万

主题

3万

帖子

10万

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
100167
发表于 2017-1-2 09:40:37
自己无聊时封装的拖动插件 任何浏览器都可用
  1. jQuery.fn.extend({
  2. Drap: function (opts) {
  3. var _self = this, _this = $(this), posX = 0, posY = 0;
  4. opts = jQuery.extend({
  5. DrapMove: null,
  6. IsLimit: false,
  7. Callback: function () { }
  8. }, opts || {});
  9. _self.mousemove = function (e) {
  10. e.stopPropagation();
  11. if ($.browser.msie) { e = window.event; }
  12. var x = e.clientX - posX;
  13. var y = e.clientY - posY;
  14. if (opts.IsLimit) {
  15. if (x < 0) {
  16. x = 0;
  17. }
  18. if (y < 0) {
  19. y = 0;
  20. }
  21. if (x > ($(document).width() - _this.width() - 2)) {
  22. x = ($(document).width() - _this.width() - 2);
  23. }
  24. if (y > ($(document).height() - _this.height() - 2)) {
  25. y = ($(document).height() - _this.height() - 2);
  26. }
  27. }
  28. _this.css("left", x + "px");
  29. _this.css("top", y + "px");
  30. //_this.find(opts.DrapMove).text("top:" + y + ",left:" + (x + _this.width()))
  31. }
  32. _this.find(opts.DrapMove).mousedown(function (e) {
  33. e.stopPropagation();
  34. if ($.browser.msie) { e = window.event; }
  35. posX = e.clientX - parseInt(_this.offset().left);
  36. posY = e.clientY - parseInt(_this.offset().top);
  37. $(document).mousemove(function (ev) {
  38. _self.mousemove(ev);
  39. });
  40. });
  41. $(document).mouseup(function () {
  42. $(document).unbind("mousemove");
  43. opts.Callback();
  44. });
  45. _this.find(opts.DrapMove).css("cursor", "move");
  46. }
  47. });
复制代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <title>Drap演示</title>
  5. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  6. <script src="drap.js" type="text/javascript"></script>
  7. <script>
  8. $(function () {
  9. $("#show").Drap({ DrapMove: "#title", IsLimit: true, Callback: function () {
  10. alert("end");
  11. }
  12. });
  13. $("#close").click(function () {
  14. alert("close");
  15. });
  16. });
  17. </script>
  18. </head>
  19. <body>
  20. <div id="show" style="position: absolute; width: 216px; height: 138px; background-color: skyblue;
  21. border: solid 1px blue;">
  22. <div id="title" style="background-color: Blue; height: 20px; color: #fff; font-size: 12px;
  23. padding-top: 5px; padding-left: 10px;">
  24. 标题 <i id="close" style="float: right; margin-right: 10px">x</i></div>
  25. 内容
  26. </div>
  27. </body>
  28. </html>
复制代码
  1. // $("弹出窗体ID").Drap({ DrapMove:拖动对象,IsLimit:是否限制范围,Callback:拖动完成后回调});
复制代码


回复

使用道具 举报