【问题标题】:How Can You Drag and Drop Inside Custom Shapes (JavaScript, jQuery UI or Interact JS)?如何在自定义形状(JavaScript、jQuery UI 或 Interact JS)中拖放?
【发布时间】:2021-10-28 09:59:16
【问题描述】:

我尝试从列表中拖放到十字圈内,如下图所示:

但是当我触摸 div 时,它可能会掉到圆圈外,我尝试使用 CSS(边框半径、溢出、剪辑路径)但没有任何效果。

您可以在这张图片中看到列表放在 Circle 之外但在 div 内。

【问题讨论】:

标签: javascript html jquery css jquery-ui


【解决方案1】:

为此,您需要碰撞检测。您需要确定一个点是否在圆内。

可以在这里看到一个例子:http://www.jeffreythompson.org/collision-detection/point-circle.php

为什么我们需要这个?我们可以使用勾股定理来获得二维空间中两个物体之间的距离!在此上下文中,a 和b 是该点与圆心之间的水平和垂直距离。

我在这里使用了演示:https://jqueryui.com/droppable/我创建了这个示例。

$(function() {
  function getCenter(el) {
    return {
      x: $(el).position().left + ($(el).width() / 2),
      y: $(el).position().top + ($(el).height() / 2)
    }
  }

  function getPoints(el) {
    return [{
      x: $(el).position().left,
      y: $(el).position().top
    }, {
      x: $(el).position().left + $(el).width(),
      y: $(el).position().top
    }, {
      x: $(el).position().left,
      y: $(el).position().top + $(el).height()
    }, {
      x: $(el).position().left + $(el).width(),
      y: $(el).position().top + $(el).height()
    }];
  }

  function pointInsideCircle(pObj, cObj) {
    var distX = pObj.x - cObj.x;
    var distY = pObj.y - cObj.y;
    var distance = Math.sqrt((distX * distX) + (distY * distY));
    if (distance <= cObj.r) {
      return true;
    }
    return false;
  }

  $("#draggable").draggable({
    revert: "invalid"
  });

  $("#droppable").droppable({
    accept: function(el) {
      var points = getPoints(el);
      var circ = getCenter(this);
      circ['r'] = $(this).width() / 2;
      return pointInsideCircle(points[0], circ);
    },
    drop: function(event, ui) {
      $(this)
        .addClass("ui-state-highlight")
        .find("p")
        .html("Dropped!");
    }
  });
});
#draggable {
  width: 100px;
  padding: 0.2em;
  float: left;
  margin: 10px 10px 10px 0;
  text-align: center;
}

#droppable {
  width: 150px;
  height: 150px;
  padding: 0.5em;
  float: left;
  margin: 10px;
  border-width: 2px;
  border-radius: 50%;
  text-align: center;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="draggable" class="ui-widget-content">
  <p>Drag me</p>
</div>

<div id="droppable" class="ui-widget-header">
  <p>Drop here</p>
</div>

在此示例中,它仅使用 Drag 元素的左上角进行检测。您可以测试每个角落,如果有,则返回 true。这类似于touch 类型的检测。

如果左上角不在圆圈内,Drop 不会接受。

【讨论】:

  • 谢谢,这是我的工作,我试着知道里面的圆点是什么,id怎么做?
  • @RamyMoustafa 我不确定你的意思。请尝试让它自己工作。如果您进一步卡住,您可以搜索另一个答案或发布另一个问题。
猜你喜欢
  • 2019-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多