【问题标题】:Create line connecting two DIVs创建连接两个 DIV 的线
【发布时间】:2022-04-01 21:47:57
【问题描述】:

我正在创建一个关系编辑器。用户创建一些元素并能够链接它们创建关系(双向)。我创建了第一部分(用户创建元素)。例如,现在我需要在用户双击一个元素时创建连接两个 DIV 的线。

我知道可能有几种方法可以做到,但实际上我不知道如何开始。 什么是起点?

$(function() {
  $("#BtInsert").button()
    .click(function() {

      var pad = "000000"
      var cor = "" + Math.floor(Math.random() * 16777215).toString(16);
      cor = "#" + pad.substring(0, pad.length - cor.length) + cor;

      var newDIV = document.createElement('div');

      $(newDIV).addClass("base")
        .appendTo($("#container"))
        .html('N')
        .dblclick(function() {
          alert('Want to start to create a line from this div to another double click');
        })
        .draggable({
          containment: "parent"
        })
        .css({
          left: Math.floor(Math.random() * ($("#container").width() - $(".base").width())),
          top: Math.floor(Math.random() * ($("#container").width() - $(".base").width()))
        })
        .css("background-color", cor);
    })
});
#BtInsert {
  top: 405px;
  width: 400px;
  position: absolute;
}
body {
  margin: 0px;
  padding: 0px;
}
#container {
  border: solid 1px #CCC;
  width: 400px;
  height: 400px;
  padding: 0;
  margin: 0;
  top: 0;
  left: 0;
  background-color: whitesmoke;
}
.base {
  height: 50px;
  width: 50px;
  top: 30px;
  left: 30px;
  border-radius: 25px;
  box-shadow: 2px 2px 2px #888888;
  vertical-alignment: middle;
  line-height: 50px;
  text-align: center;
  margin-bottom: 5px;
  font-family: Calibri;
  font-weight: bold;
  font-size: 2em;
  color: white;
  background-color: #CCC;
  cursor: pointer;
  -webkit-transition: width 3s, height 3s, border-radius 3s, line-height 3s, box-shadow 3s;
  transition: width 3s, height 3s, border-radius 3s, line-height 3s, box-shadow 3s;
  float: left;
  position: absolute;
  z-index: 0;
}
.base:hover {
  z-index: 1000;
  color: #333;
  width: 80px;
  height: 80px;
  border-radius: 50px;
  line-height: 80px;
  box-shadow: 4px 4px 4px #888888;
  -webkit-transition: width 1s, height 1s, border-radius 1s, line-height 1s, box-shadow 1s;
  transition: width 1s, height 1s, border-radius 1s, line-height 1s, box-shadow 1s;
}
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>


<div id="container">
</div>
<a href="#" id="BtInsert">
    Insert an element
</a>

JS Fiddle

【问题讨论】:

  • 您的问题并非完全重复,因为您要求动态创建线条,但您可以查看this answer 了解如何创建线条。

标签: javascript jquery html css


【解决方案1】:

这种表示形式最好使用 SVG 而不是 HTML。您将在 SVG 中更灵活地绘制形状。

你可以看看http://d3js.org/http://raphaeljs.com/

看这个例子:

它正在做与你想要的类似的事情。

【讨论】:

猜你喜欢
  • 2023-03-17
  • 2013-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-12
  • 1970-01-01
  • 1970-01-01
  • 2010-10-07
相关资源
最近更新 更多