首页 > 解决方案 > 拖动元素时两个 div droppables 的问题(Jquery Ui)

问题描述

我对 Jquery Ui Droppable 有疑问。

我在一个 div 容器中有两个 div droppables,当我选择紫色框并将它首先拖动到第二个 div 然后到第一个时,div 容器与第一个 div 一起被选中,这是我遇到的错误,在 JsFiddle 中,当我在它上面时,红色会在它周围打开。我在互联网上环顾四周,但找不到解决方案。如果我将紫色框拖到第一个 div,然后再拖到第二个,它可以正常工作,但反之则不行。我附上了一张图片在JsFiddle中显示了错误谢谢

JsFiddle: https ://jsfiddle.net/7unvxgqo/

$(document).ready(function () {


$("#draggable2").draggable({
    // opacity : 0.7, 
    helper: "clone",
    scope: 1,
    start: function (e, ui) {
        $(ui.helper).addClass("drag-helper");

        //console.log(ui);
    }
});


$(".draggable3").droppable({
    greedy: true,
    tolerance: 'pointer',
    scope: 1


});


$("#droppable").droppable({
    //Over
    greedy: true,
    tolerance: 'pointer',

    scope: 1
})

});

图片:

在第一个 div 中拖动元素时,红色边框处于活动状态

标签: jqueryjquery-ui

解决方案


一种解决方法可能是在两个嵌套元素之间添加一个小边距。

示例:https ://jsfiddle.net/Twisty/aL32ru7d/16/

HTML

<div id="draggable2" class="draggable">
</div>
<div class="container">
  <div id="drop-1" class="drop-zone">
    <p>Drop here</p>
    <div id="drop-nest-1" class="drop-nest">
      <p>First Div</p>
    </div>
    <div id="drop-nest-2" class="drop-nest">
      <p>Second Div</p>
    </div>
  </div>
</div>

CSS

.drop-nest {
  width: 100%;
  height: 100px;
  background: #0066CC;
  border: 2px solid #00FF00;
  margin-bottom: 6px;
}

#draggable2 {
  height: 100px;
  width: 100px;
  background-color: #CC33CC;
  margin-bottom: 3em;
}

.drop-zone {
  width: 100%;
  height: 500px;
  padding: 0;
  border: 5px solid black;
  background-color: #777;
  margin: 0px !important;
}

.drag-helper {
  width: 50px;
  height: 50px;
  padding: 0px;
  border: 5px solid gray;
  background-color: #CC33CC;
}

.container {
  width: 100%;
  padding: 0px !important;
  margin: 0px !important;
}

.my-hover {
  border: 5px dashed #FF0000 !important;
}

body,
html {
  margin: 0px;
}

JavaScript

$(function() {
  $("#draggable2").draggable({
    // opacity : 0.7, 
    helper: "clone",
    scope: 1,
    start: function(e, ui) {
      $(ui.helper).addClass("drag-helper");
    }
  });

  $(".drop-zone, .drop-nest").droppable({
    greedy: true,
    tolerance: 'pointer',
    scope: 1,
    over: function(e, ui) {
      $(this).addClass("my-hover");
    },
    out: function(e, ui) {
      $(this).removeClass("my-hover");
    }
  });
});

该问题似乎与greedy选项和out. 一瞬间,鼠标位置触发两者以检测over. 留出一点空间可以让鼠标选择其中一个元素而不是两者。这里需要注意的是,如果鼠标移动得非常快,它仍然会触发问题。

我选择6px了,但我测试了许多值。间隙越小,越容易触发。


推荐阅读