javascript – JS绘制一个从一个div指向另一个div的箭头

我有以下代码:

<div id="parent">
  <div class="child" id="air1">Medium 1</div>
  <div class="child" id="glass">Medium 2</div>
  <div class="child" id="air2">Medium 1</div>
</div>

<style>
  #parent {
    background: #999;
    padding: 0px;
  }
  #glass {
    background: #666;
  }
  .child {
    background: #ccc;
    height: 200px;
    margin: 0px;
  }
</style>

我想使用svg从#air1中将箭头绘制成#glass.我将以下代码添加到div中以绘制示例箭头:

<svg width="300" height="100">

    <defs>
        <marker id="arrow" markerWidth="13" markerHeight="13" refx="2" refy="6" orient="auto">
            <path d="M2,2 L2,11 L10,6 L2,2" style="fill:red;" />
        </marker>
    </defs>

    <path d="M30,150 L100,50"
          style="stroke:red; stroke-width: 1.25px; fill: none;
                 marker-end: url(#arrow);"
    />

</svg>

我不希望箭头指向一个随机的方向,我希望它指向#glass像这样:《javascript – JS绘制一个从一个div指向另一个div的箭头》

另外,我如何绘制这样一个不那么陡峭的箭头:
《javascript – JS绘制一个从一个div指向另一个div的箭头》

我怎样才能做到这一点?

最佳答案 您可以使用
positioning(将svg插入第一部分并将其设置为position:absolute;)并调整path元素的偏移量来实现.要使箭头指向下方,只需对路径描述属性的第二个值使用负值.

有关更多信息,请参阅w3schools about path.

#parent {
  background: #999;
  padding: 0px;
}
#glass {
  background: #666;
}
.child {
  background: #ccc;
  height: 200px;
  margin: 0px;
  position: relative;
}
svg {
  position: absolute;
  left: 0;
}
<div id="parent">
  <div class="child" id="air1">Medium 1
    <svg width="400" height="200">
      <defs>
        <marker id="arrow" markerWidth="13" markerHeight="13" refx="2" refy="6" orient="auto">
          <path d="M2,2 L2,11 L10,6 L2,2" style="fill:red;" />
        </marker>
      </defs>
      <path d="M-600,-10 L300,195" style="stroke:red; stroke-width: 1.25px; fill: none; marker-end: url(#arrow);" />
    </svg>
  </div>
  <div class="child" id="glass">Medium 2</div>
  <div class="child" id="air2">Medium 1</div>
</div>
点赞