如何使用 JavaScript 或 jQuery 同时拖动多个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5677993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:24:42  来源:igfitidea点击:

How do I drag multiple elements at once with JavaScript or jQuery?

javascriptjqueryjquery-uijquery-pluginsdrag-and-drop

提问by js_

I want to be able to drag a group of elements with jQuery, like if I selected and dragged multiple icons on the Windows desktop.

我希望能够使用 jQuery 拖动一组元素,就像我在 Windows 桌面上选择并拖动多个图标一样。

I found the demo of threedubmedia's jQuery.event.drag:

我找到了Threedubmedia 的 jQuery.event.drag的演示:

http://threedubmedia.com/code/event/drag/demo/multi
http://threedubmedia.com/code/event/drag#demos

http://threedubmedia.com/code/event/drag/demo/multi
http://threedubmedia.com/code/event/drag#demos

I think this plugin is great. Is this good and popular library? Do you know websites or applications which use it?

我觉得这个插件很棒。这是一个很好的和流行的图书馆吗?您知道使用它的网站或应用程序吗?

Are there any other libraries or plugins to drag multiple objects?

是否有其他库或插件可以拖动多个对象?

Can jQuery UIdrag multiple objects?

可以jQuery UI的拖动多个对象?

采纳答案by Naftali aka Neal

there is Draggablein the jquery UI

jquery UI 中有Draggable

all you would have to do is:

您所要做的就是:

$(selector).draggable(); // and you are done!

see example here: http://jsfiddle.net/maniator/zVZFq/

请参阅此处的示例:http: //jsfiddle.net/maniator/zVZFq/



If you really want multidragging you can try using some click events to hold the blocks in place

如果你真的想要多拖动,你可以尝试使用一些点击事件来固定块

$('.drag').draggable();

$('.drag').click(function(){
    console.log(this, 'clicked')
    var data = $(this).data('clicked');
    var all = $('.all');
    if(data == undefined || data == false){
        $(this).data('clicked', true);
        this.style.background = 'red';
        $(this).draggable('disable');
        if(all.children().length <= 0){
            all.draggable().css({
                top: '0px',
                left: '0px',
                width: $(window).width(),
                height: $(window).height(),
                'z-index': 1
            });
        }
        var top = parseInt(all.css('top').replace('px','')) +
                    parseInt($(this).css('top').replace('px',''))
        var left = parseInt(all.css('left').replace('px','')) +
                    parseInt($(this).css('left').replace('px',''))
        $(this).css({
            top: top,
            left: left
        })
        $('.all').append($(this));
    }
    else {
        $(this).data('clicked', false);
        this.style.background = 'grey';
        $(this).draggable('enable');
        $('body').append($(this));
        if(all.children() <= 0){
            all.draggable('destroy');
        }
        /*
        var top = parseInt(all.css('top').replace('px','')) -
                    parseInt($(this).css('top').replace('px',''))
        var left = parseInt(all.css('left').replace('px','')) -
                    parseInt($(this).css('left').replace('px',''))
        $(this).css({
            top: top,
            left: left
        })*/
    }
})

See example here: http://jsfiddle.net/maniator/zVZFq/5

请参阅此处的示例:http: //jsfiddle.net/maniator/zVZFq/5

回答by mike.helgeson

I am the author of the of the threedubmedia plugins. I added this functionality for supporting multiple elements, because I could not find a satisfactory solution anywhere else.

我是threedubmedia 插件的作者。我添加了此功能以支持多个元素,因为我在其他任何地方都找不到令人满意的解决方案。

If you need a solution that works with the jQuery UI, here is a plugin which adds some multi-drag functionality, though the demos don't seem to work correctly in Firefox for Mac.

如果您需要一个适用于 jQuery UI 的解决方案,这里有一个插件,它添加了一些多拖动功能,尽管演示在 Firefox for Mac 中似乎无法正常工作。

http://www.myphpetc.com/2009/11/jquery-ui-multiple-draggable-plugin.html

http://www.myphpetc.com/2009/11/jquery-ui-multiple-draggable-plugin.html

回答by ChrisThompson

var selectedObjs;
var draggableOptions = {
    start: function(event, ui) {
        //get all selected...
        selectedObjs = $('div.selected').filter('[id!='+$(this).attr('id')+']');
    },
    drag: function(event, ui) {
        var currentLoc = $(this).position();
        var orig = ui.originalPosition;

        var offsetLeft = currentLoc.left-orig.left;
        var offsetTop = currentLoc.top-orig.top;

        moveSelected(offsetLeft, offsetTop);
    }       
};

$(document).ready(function() {
    $('#dragOne, #dragTwo').draggable(draggableOptions);
});

function moveSelected(ol, ot){
    console.log(selectedObjs.length);
    selectedObjs.each(function(){
        $this =$(this);
        var pos = $this.position();

        var l = $this.context.clientLeft;
        var t = $this.context.clientTop;

        $this.css('left', l+ol);
        $this.css('top', t+ot);
    })
}

回答by Riccardo Di Stefano

This worked for me.

这对我有用。

Fiddle here:

在这里小提琴:

var selectedObjs;
var draggableOptions = {
start: function(event, ui) {
    //get all selected...
    if (ui.helper.hasClass('selected')) selectedObjs = $('div.selected');
    else {
        selectedObjs = $(ui.helper);
        $('div.selected').removeClass('selected')
    }
},
drag: function(event, ui) {
    var currentLoc = $(this).position();
    var prevLoc = $(this).data('prevLoc');
    if (!prevLoc) {
        prevLoc = ui.originalPosition;
    }

    var offsetLeft = currentLoc.left-prevLoc.left;
    var offsetTop = currentLoc.top-prevLoc.top;

    moveSelected(offsetLeft, offsetTop);
    selectedObjs.each(function () {
           $(this).removeData('prevLoc');
        });
    $(this).data('prevLoc', currentLoc);
}
};

$('.drag').draggable(draggableOptions).click(function()     {$(this).toggleClass('selected')});


function moveSelected(ol, ot){
console.log("moving to: " + ol + ":" + ot);
selectedObjs.each(function(){
    $this =$(this);
    var p = $this.position();
    var l = p.left;
    var t = p.top;
    console.log({id: $this.attr('id'), l: l, t: t});


    $this.css('left', l+ol);
    $this.css('top', t+ot);
})
}

Thanks to ChrisThompson and green for the almost-perfect solution.

感谢 ChrisThompson 和 green 提供了几乎完美的解决方案。

回答by Sudheer Someshwara

Check this out:

看一下这个:

https://github.com/someshwara/MultiDraggable

https://github.com/someshwara/MultiDraggable

Usage:$(".className").multiDraggable({ group: $(".className")});

用法:$(".className").multiDraggable({ group: $(".className")});

Drags the group of elements together. Group can also be an array specifying individual elements.

将一组元素拖到一起。Group 也可以是指定单个元素的数组。

Like:$("#drag1").multiDraggable({ group: [$("#drag1"),$("#drag2") ]});

喜欢:$("#drag1").multiDraggable({ group: [$("#drag1"),$("#drag2") ]});

回答by Wyck

I wanted to add (this coming up high in google), since none of the plugins in this thread worked and it is not nativity supported by jquery ui, a simple elegant solution.

我想补充一下(这在 google 中很受欢迎),因为这个线程中的插件都没有工作,而且 jquery ui 不支持它的诞生,这是一个简单而优雅的解决方案。

Wrap the draggable elements in a container and use an event to drag them all at once, this allows for singles draggables and multidraggables (but not really selective draggables).

将可拖动元素包装在一个容器中并使用一个事件将它们一次性全部拖动,这允许单个可拖动元素和多可拖动元素(但不是真正的选择性可拖动元素)。

jQuery(document).click(function(e) {

  if(e.shiftKey) {
      jQuery('#parent-container').draggable();
  }
}); 

回答by Ev_genus

Put your items into some container and make this container draggable. You will need to set handleoption to be a class of your item element. Also you will need to recalculate items position after drag. And obviously when you deselect items you have to take them from this container and put back to their origin.

将您的项目放入某个容器中并使该容器可拖动。您需要将handle选项设置为您的项目元素的类。您还需要在拖动后重新计算项目位置。很明显,当您取消选择项目时,您必须将它们从这个容器中取出并放回原处。

回答by Sjoerd de Wit

This is what i used, Worked in my case.

这就是我使用的,在我的情况下有效。

function selectable(){
$('#selectable').selectable({
  stop: function() {
    $('.ui-selectee', this).each(function(){
        if ($('.ui-selectee').parent().is( 'div' ) ) {
            $('.ui-selectee li').unwrap('<div />');
        }


    });

    $('.ui-selected').wrapAll('<div class=\"draggable\" />');

    $('.draggable').draggable({ revert : true });   
  }
});

};

};