没有jQuery UI的可拖动div

正如标题所说,我试图让一个div可拖动,而不使用jQuery UI。

不过,我被下面的代码填塞了。 我知道我将使用相对于容器div的鼠标位置(div将被拖动),并且我将设置相对于这些值的div偏移量。

我只是不知道如何。 任何线索对我来说?

此代码不(当然)工作:

var X, Y; $(this).mousedown(function() { $(this).offset({ left: X, top: Y }); }); $("#containerDiv").mousemove(function(event) { X = event.pageX; Y = event.pageY; }); 

下面是一个非常简单的例子,可以帮助你开始:

 $(document).ready(function() { var $dragging = null; $(document.body).on("mousemove", function(e) { if ($dragging) { $dragging.offset({ top: e.pageY, left: e.pageX }); } }); $(document.body).on("mousedown", "div", function (e) { $dragging = $(e.target); }); $(document.body).on("mouseup", function (e) { $dragging = null; }); }); 

例如: http : //jsfiddle.net/Jge9z/

我知道我将使用相对于容器div的鼠标位置(div将被拖动),并且我将设置相对于这些值的div偏移量。

不太确定。 在我看来,在拖放中你总是要使用元素相对于文档的偏移量。

如果你的意思是你想限制拖动到一个特定的领域,这是一个更复杂的问题(但仍然可行)。

这是另一个更新的代码:

 $(document).ready(function() { var $dragging = null; $('body').on("mousedown", "div", function(e) { $(this).attr('unselectable', 'on').addClass('draggable'); var el_w = $('.draggable').outerWidth(), el_h = $('.draggable').outerHeight(); $('body').on("mousemove", function(e) { if ($dragging) { $dragging.offset({ top: e.pageY - el_h / 2, left: e.pageX - el_w / 2 }); } }); $dragging = $(e.target); }).on("mouseup", ".draggable", function(e) { $dragging = null; $(this).removeAttr('unselectable').removeClass('draggable'); }); });​ 

演示: http : //jsfiddle.net/tovic/Jge9z/31/


我为这个线程创build了一个简单的插件。

 // Simple JQuery Draggable Plugin // https://plus.google.com/108949996304093815163/about // Usage: $(selector).drags(); // Options: // handle => your dragging handle. // If not defined, then the whole body of the // selected element will be draggable // cursor => define your draggable element cursor type // draggableClass => define the draggable class // activeHandleClass => define the active handle class // // Update: 26 February 2013 // 1. Move the `z-index` manipulation from the plugin to CSS declaration // 2. Fix the laggy effect, because at the first time I made this plugin, // I just use the `draggable` class that's added to the element // when the element is clicked to select the current draggable element. (Sorry about my bad English!) // 3. Move the `draggable` and `active-handle` class as a part of the plugin option // Next update?? NEVER!!! Should create a similar plugin that is not called `simple`! (function($) { $.fn.drags = function(opt) { opt = $.extend({ handle: "", cursor: "move", draggableClass: "draggable", activeHandleClass: "active-handle" }, opt); var $selected = null; var $elements = (opt.handle === "") ? this : this.find(opt.handle); $elements.css('cursor', opt.cursor).on("mousedown", function(e) { if(opt.handle === "") { $selected = $(this); $selected.addClass(opt.draggableClass); } else { $selected = $(this).parent(); $selected.addClass(opt.draggableClass).find(opt.handle).addClass(opt.activeHandleClass); } var drg_h = $selected.outerHeight(), drg_w = $selected.outerWidth(), pos_y = $selected.offset().top + drg_h - e.pageY, pos_x = $selected.offset().left + drg_w - e.pageX; $(document).on("mousemove", function(e) { $selected.offset({ top: e.pageY + pos_y - drg_h, left: e.pageX + pos_x - drg_w }); }).on("mouseup", function() { $(this).off("mousemove"); // Unbind events from document if ($selected !== null) { $selected.removeClass(opt.draggableClass); $selected = null; } }); e.preventDefault(); // disable selection }).on("mouseup", function() { if(opt.handle === "") { $selected.removeClass(opt.draggableClass); } else { $selected.removeClass(opt.draggableClass) .find(opt.handle).removeClass(opt.activeHandleClass); } $selected = null; }); return this; }; })(jQuery); 

演示: http : //tovic.github.io/dte-project/jquery-draggable/index.html

这是我的贡献:

http://jsfiddle.net/g6m5t8co/1/

 <!doctype html> <html> <head> <style> #container { position:absolute; background-color: blue; } #elem{ position: absolute; background-color: green; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; -ms-user-select: none; -khtml-user-select: none; user-select: none; } </style> <script> var mydragg = function(){ return { move : function(divid,xpos,ypos){ divid.style.left = xpos + 'px'; divid.style.top = ypos + 'px'; }, startMoving : function(divid,container,evt){ evt = evt || window.event; var posX = evt.clientX, posY = evt.clientY, divTop = divid.style.top, divLeft = divid.style.left, eWi = parseInt(divid.style.width), eHe = parseInt(divid.style.height), cWi = parseInt(document.getElementById(container).style.width), cHe = parseInt(document.getElementById(container).style.height); document.getElementById(container).style.cursor='move'; divTop = divTop.replace('px',''); divLeft = divLeft.replace('px',''); var diffX = posX - divLeft, diffY = posY - divTop; document.onmousemove = function(evt){ evt = evt || window.event; var posX = evt.clientX, posY = evt.clientY, aX = posX - diffX, aY = posY - diffY; if (aX < 0) aX = 0; if (aY < 0) aY = 0; if (aX + eWi > cWi) aX = cWi - eWi; if (aY + eHe > cHe) aY = cHe -eHe; mydragg.move(divid,aX,aY); } }, stopMoving : function(container){ var a = document.createElement('script'); document.getElementById(container).style.cursor='default'; document.onmousemove = function(){} }, } }(); </script> </head> <body> <div id='container' style="width: 600px;height: 400px;top:50px;left:50px;"> <div id="elem" onmousedown='mydragg.startMoving(this,"container",event);' onmouseup='mydragg.stopMoving("container");' style="width: 200px;height: 100px;"> <div style='width:100%;height:100%;padding:10px'> <select id=test> <option value=1>first <option value=2>second </select> <INPUT TYPE=text value="123"> </div> </div> </div> </body> </html> 

这里是制作一个以点击为中心的可拖动对象的另一种方法

http://jsfiddle.net/pixelass/fDcZS/

 function endMove() { $(this).removeClass('movable'); } function startMove() { $('.movable').on('mousemove', function(event) { var thisX = event.pageX - $(this).width() / 2, thisY = event.pageY - $(this).height() / 2; $('.movable').offset({ left: thisX, top: thisY }); }); } $(document).ready(function() { $("#containerDiv").on('mousedown', function() { $(this).addClass('movable'); startMove(); }).on('mouseup', function() { $(this).removeClass('movable'); endMove(); }); }); 

CSS

 #containerDiv { background:#333; position:absolute; width:200px; height:100px; } 

像jQueryUI拖动: JsFiddle

您可以从任何点拖动元素,而不会奇怪居中。

 $(document).ready(function() { var $body = $('body'); var $target = null; var isDraggEnabled = false; $body.on("mousedown", "div", function(e) { $this = $(this); isDraggEnabled = $this.data("draggable"); if (isDraggEnabled) { if(e.offsetX==undefined){ x = e.pageX-$(this).offset().left; y = e.pageY-$(this).offset().top; }else{ x = e.offsetX; y = e.offsetY; }; $this.addClass('draggable'); $body.addClass('noselect'); $target = $(e.target); }; }); $body.on("mouseup", function(e) { $target = null; $body.find(".draggable").removeClass('draggable'); $body.removeClass('noselect'); }); $body.on("mousemove", function(e) { if ($target) { $target.offset({ top: e.pageY - y, left: e.pageX - x }); }; }); }); 

这是我的。 http://jsfiddle.net/pd1vojsL/

在div中拖动3个button,由div限制拖动。

 <div id="parent" class="parent"> <button id="button1" class="button">Drag me</button> <button id="button2" class="button">Drag me</button> <button id="button3" class="button">Drag me</button> </div> <div id="log1"></div> <div id="log2"></div> 

需要JQuery(仅):

 $(function() { $('.button').mousedown(function(e) { if(e.which===1) { var button = $(this); var parent_height = button.parent().innerHeight(); var top = parseInt(button.css('top')); //current top position var original_ypos = button.css('top','').position().top; //original ypos (without top) button.css({top:top+'px'}); //restore top pos var drag_min_ypos = 0-original_ypos; var drag_max_ypos = parent_height-original_ypos-button.outerHeight(); var drag_start_ypos = e.clientY; $('#log1').text('mousedown top: '+top+', original_ypos: '+original_ypos); $(window).on('mousemove',function(e) { //Drag started button.addClass('drag'); var new_top = top+(e.clientY-drag_start_ypos); button.css({top:new_top+'px'}); if(new_top<drag_min_ypos) { button.css({top:drag_min_ypos+'px'}); } if(new_top>drag_max_ypos) { button.css({top:drag_max_ypos+'px'}); } $('#log2').text('mousemove min: '+drag_min_ypos+', max: '+drag_max_ypos+', new_top: '+new_top); //Outdated code below (reason: drag contrained too early) /*if(new_top>=drag_min_ypos&&new_top<=drag_max_ypos) { button.css({top:new_top+'px'}); }*/ }); $(window).on('mouseup',function(e) { if(e.which===1) { //Drag finished $('.button').removeClass('drag'); $(window).off('mouseup mousemove'); $('#log1').text('mouseup'); $('#log2').text(''); } }); } }); }); 

你甚至不需要jQuery来创build可拖动的交互性! 结帐下面的codepen:

http://codepen.io/anon/pen/VPPaEK

它基本上在需要拖动的元素上设置一个“mousedown”事件,然后绑定和解绑文档mousemove来处理运动。

最基本的可拖动代码将是:

 Element.prototype.drag = function(){ var mousemove = function(e){ // document mousemove this.style.left = e.clientX+'px'; this.style.top = e.clientY+'px'; }.bind(this); var mouseup = function(e){ // document mouseup document.removeEventListener('mousemove',mousemove); document.removeEventListener('mouseup',mouseup); }.bind(this); this.addEventListener('mousedown',function(e){ // element mousedown document.addEventListener('mousemove',mousemove); document.addEventListener('mouseup',mouseup); }.bind(this)); } 

然后用法(非jquery):

 document.querySelector('.dragElement').drag(); 

或在jQuery中:

 $('.dragElement')[0].drag(); 

注意:拖动的元素应该有一个位置:绝对或位置:固定应用于它的左侧,顶部运动工作…

上面的codepen包括更多的“高级”function:dragStart,dragStopcallback,css类附加删除其他元素拖动时的文本select,和一个下降function也…

 $(document).ready(function() { var $startAt = null; $(document.body).live("mousemove", function(e) { if ($startAt) { $("#someDiv").offset({ top: e.pageY, left: $("#someDiv").position().left-$startAt+e.pageX }); $startAt = e.pageX; } }); $("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;}); $(document.body).live("mouseup", function (e) {$startAt = null;}); }); 

这是我的简单版本。
draggable函数将一个jQuery对象作为参数。

 /** * @param {jQuery} elem */ function draggable(elem){ elem.mousedown(function(evt){ var x = parseInt(this.style.left || 0) - evt.pageX; var y = parseInt(this.style.top || 0) - evt.pageY; elem.mousemove(function(evt){ elem.css('left', x + evt.pageX); elem.css('top', y + evt.pageY); }); }); elem.mouseup(off); elem.mouseleave(off); function off(){ elem.off("mousemove"); } } 

这里是一个不使用jQuery的实现 –
http://thezillion.wordpress.com/2012/09/27/javascript-draggable-2-no-jquery

在你的HTML代码中embeddedJS文件(http://zillionhost.xtreemhost.com/tzdragg/tzdragg.js),并把下面的代码; –

 <script> win.onload = function(){ tzdragg.drag('elem1, elem2, ..... elemn'); // ^ IDs of the draggable elements separated by a comma. } </script> 

而且代码也很容易学习。
http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery