如何在jQuery中创建一个可拖动的元素?

如何使用jQuery创建一个元素,例如div,draggable?

首先加载jQuery UI:

   

然后使用jQuery UI draggable方法 :

  

你可以只使用jquery,没有jquery UI:

 function handle_mousedown(e){ window.my_dragging = {}; my_dragging.pageX0 = e.pageX; my_dragging.pageY0 = e.pageY; my_dragging.elem = this; my_dragging.offset0 = $(this).offset(); function handle_dragging(e){ var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0); var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0); $(my_dragging.elem) .offset({top: top, left: left}); } function handle_mouseup(e){ $('body') .off('mousemove', handle_dragging) .off('mouseup', handle_mouseup); } $('body') .on('mouseup', handle_mouseup) .on('mousemove', handle_dragging); } $('#b').mousedown(handle_mousedown); 

我刚刚做了这个,所以它非常便携,而不是在整个jQuery UI中“拖动”。

它在下面拖动时不会选择文本,所以这实际上在生产中不同于此处的其他代码。

这也适用于固定定位元素非常好,所以你可以“停靠”

 $.fn.draggable = function(){ var $this = this, ns = 'draggable_'+(Math.random()+'').replace('.',''), mm = 'mousemove.'+ns, mu = 'mouseup.'+ns, $w = $(window), isFixed = ($this.css('position') === 'fixed'), adjX = 0, adjY = 0; $this.mousedown(function(ev){ var pos = $this.offset(); if (isFixed) { adjX = $w.scrollLeft(); adjY = $w.scrollTop(); } var ox = (ev.pageX - pos.left), oy = (ev.pageY - pos.top); $this.data(ns,{ x : ox, y: oy }); $w.on(mm, function(ev){ ev.preventDefault(); ev.stopPropagation(); if (isFixed) { adjX = $w.scrollLeft(); adjY = $w.scrollTop(); } var offset = $this.data(ns); $this.css({left: ev.pageX - adjX - offset.x, top: ev.pageY - adjY - offset.y}); }); $w.on(mu, function(){ $w.off(mm + ' ' + mu).removeData(ns); }); }); return this; }; 

但是这假设绝对或固定定位已经应用于元素。

像这样使用它:

 $('#something').draggable(); 

你真正需要的只是我自己组装的jQuery脚本:和代码$(’#yourElement’)。draggable();

 $(document).ready(function() { $('#dragMe').draggable(); }); 
 #dragMe { width: 100px; height: 100px; background: #bbb; border-top: 3px solid #eee; border-left: 3px solid #ddd; border-right: 3px solid #666; border-bottom: 3px solid #555; position: absolute; cursor: grab; } p { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); margin: 0; white-space: nowrap; font-size: 12px; font-family: Helvetica, Arial, sans-serif; font-weight: 100; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } #dragMe:active { cursor: grabbing; } 
  

Drag Me Around