【问题标题】:JS draw an arrow pointing from one div to anotherJS 绘制一个从一个 div 指向另一个 div 的箭头
【发布时间】:2016-09-12 06:39:14
【问题描述】:

我有以下代码:

<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 css html svg


    【解决方案1】:

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

    欲了解更多信息,请参阅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>

    【讨论】:

    • 这正是我所需要的!如果我想让箭头像thisthis 那样陡峭,我想调整什么值
    • 更新了答案。为 svg 设置 left: 0; 并使用路径描述符,例如第一个值可以影响角度
    • 你介意给我一个指南或文档吗?就像我需要一种方法来学习如何一次为多个箭头执行此操作
    • 用带有示例的 w3schools 页面更新了答案
    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 2019-01-27
    • 2013-11-18
    • 2023-03-03
    相关资源
    最近更新 更多