简单的jQuery draggable实现没有jQuery-UI – 如何关闭?

我在这里定制了一个简化的“可拖动”函数: 没有jQuery-UI的可拖动,这是我到目前为止所拥有的:

$.fn.extend({ canDragMe: function(){ return this.each(function() { var $this = $(this); $this = $(this); return $this.css('cursor', opt.cursor).on("mousedown", function(e) { var $drag = $this.addClass('draggable'); drg_h = $drag.outerHeight(), drg_w = $drag.outerWidth(), pos_y = $drag.offset().top + drg_h - e.pageY, pos_x = $drag.offset().left + drg_w - e.pageX; $drag.on("mousemove", function(e) { $('.draggable').offset({ top:e.pageY + pos_y - drg_h, left:e.pageX + pos_x - drg_w }).on("mouseup", function() { $this.removeClass('draggable'); }); }); e.preventDefault(); // disable selection }).on("mouseup", function() { $this.removeClass('draggable'); } }); }); }); 

我打算像这样使用它: $('#mydiv').canDragMe(); 。 但是我需要根据用户输入在元素上打开和关闭拖动。

所以我的问题是,关闭阻力最简单的方法是什么? 要么是$('#mydiv').canNotDragMe(); 或者是$('#mydiv').canDragMe(false); (当然,这需要插件中的输入选项)。

编辑

我明白我需要某种实现解除上面mousedown的操作? 或者某种方式来“破坏”插件?

您可以通过简单地解除在原始方法中设置的处理程序来创建基本的cannotDragMe方法。 由于原始使用.on() ,您可以使用.on()在新方法中关闭它们。

注意:我还注意到您提供的代码与您引用的网站上的代码不同。 网站上的代码具有更好的性能,因此我使用了它。 我还在.on().on()事件中添加了名称空间 ,这样您就不会意外解除任何不打算取消绑定的内容。

更新了jQuery Extend方法 – jsfiddle

 $.fn.extend({ cannotDragMe: function () { return this.each(function () { var $this = $(this); $this = $(this); return $this.css('cursor', 'default').off("mousedown.drag").off("mousemove.drag").off("mouseup.drag"); }); }, canDragMe: function (opt) { opt = $.extend({ handle: "", cursor: "move" }, opt); var $el; if (opt.handle === "") { $el = this; } else { $el = this.find(opt.handle); } return $el.css('cursor', opt.cursor).on("mousedown.drag", function (e) { var $drag; if (opt.handle === "") { $drag = $(this).addClass('draggable'); } else { $drag = $(this).addClass('active-handle').parent().addClass('draggable'); } var z_idx = $drag.css('z-index'), drg_h = $drag.outerHeight(), drg_w = $drag.outerWidth(), pos_y = $drag.offset().top + drg_h - e.pageY, pos_x = $drag.offset().left + drg_w - e.pageX; $drag.css('z-index', 1000).parents().on("mousemove.drag", function (e) { $('.draggable').offset({ top: e.pageY + pos_y - drg_h, left: e.pageX + pos_x - drg_w }).on("mouseup.drag", function () { $(this).removeClass('draggable').css('z-index', z_idx); }); }); e.preventDefault(); // disable selection }).on("mouseup.drag", function () { if (opt.handle === "") { $(this).removeClass('draggable'); } else { $(this).removeClass('active-handle').parent().removeClass('draggable'); } }); } });