javascript - 一次只允许一个 draggable 在一个 droppable 中,允许任何一个被删除

标签 javascript jquery html css jquery-ui

这是我目前可拖放部分的内容:

$('.planets').draggable({
    opacity: .4,
    create: function(){$(this).data('position',$(this).position())},
    cursorAt:{left:15},
    cursor:'move',
    start:function(){$(this).stop(true,true)},
    revert : 'invalid'
});

$('.targets').droppable({
    greedy: true, ///////////////
  drop: function( event, ui ) {
    $( this ).addClass( "dropped-highlight" );
    $(this).droppable('option', 'accept', ui.draggable); ////////
    $(this).append(ui.draggable); /////////
    snapToMiddle(ui.draggable,$(this)); //This function snaps the draggable to the middle of the droppable
  },
  out: function( event, ui ) {
    $(this).removeClass( "dropped-highlight" );
    $(this).droppable('option', 'accept', '.planets'); /////////
  }
});

目前,我可以将多个可拖动对象堆叠在一个可放置对象中。我只想一次允许任何一个可拖放的可拖放。删除可拖动对象后,新的可拖动对象可以进入该区域。带有///////的代码行是我最近添加的代码行,目的是尝试实现这一目标。

编辑:这行得通!

$('.planets').draggable({
    opacity: .4,
    create: function(){$(this).data('position',$(this).position())},
    cursorAt:{left:15},
    cursor:'move',
    start:function(){$(this).stop(true,true)},
    revert : 'invalid'
});

$('.targets').droppable({
  drop: function( event, ui ) {
    if(!$(this).hasClass('dropped-highlight')){
        $( this ).addClass( "dropped-highlight" );
        $(this).droppable('option', 'accept', ui.draggable);
    }
  },
  out: function( event, ui ) {
    $(this).droppable('option', 'accept', '.planets');
            $(this).removeClass( "dropped-highlight" );
  }
});

最佳答案

在追加元素之前检查“dropped-highlight”类是否存在,并在 droppable 声明的“out”部分删除它。

类似于(伪代码):

if !this.hasClass('dropped-highlight'){

(你的代码)

并在下降: this.removeClass('dropped-highlight').

您已经准备好第二件事,只需添加第一件事。

if !$(this).hasClass("dropped-highlight"){
  $( this ).addClass( "dropped-highlight" );
  $(this).droppable('option', 'accept', ui.draggable);
}

关于javascript - 一次只允许一个 draggable 在一个 droppable 中,允许任何一个被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23529380/

相关文章:

javascript - Rhino JS 解释器与 SpiderMonkey 解释器 - 不同的返回值

javascript - 使用 Bootstrap 设置我的导航栏事件链接

javascript - 刷新后动态字段仍然可见

html - CSS - 响应图像大小

php - htmlentities($password_string) 是必要的吗?

javascript - 将选定的选项复制到另一个选择

javascript - .ns() 在谷歌 Angular map 指令中未定义

JQuery 如何从存储在变量中的一组对象中搜索可见元素

javascript - 自定义删除 DOM 元素问题

php - 在 PHP 中使用缩进和格式化项目进行选择