【问题标题】:connecting divs with svg line用 svg 线连接 div
【发布时间】:2022-01-20 01:07:11
【问题描述】:
  for (el of chart.children) {
    i++
    previous__element = chart.children[i - 1]
    if (el.classList.contains('rule')) {
      //pass 

    } else {
      line = el.children[0].children[0]

      pos1 = previous__element.children[2].getBoundingClientRect()

      position1 = {
        top: pos1.top,
        left: pos1.left,
      }

      pos2 = el.children[2].getBoundingClientRect()

      console.log(previous__element.children[2])
      console.log(el.children[2])

      position2 = {
        top: pos2.top,
        left: pos2.left,
      }

      line.setAttribute('x1', Math.trunc(pos1.left))
      line.setAttribute('y1', Math.trunc(pos1.top))
      line.setAttribute('x2', Math.trunc(pos1.left))
      line.setAttribute('y2', Math.trunc(pos1.top))
      line.setAttribute('stroke', 'white')
    }
  }

获取输出的html:

由于某种原因,这实际上并没有显示线条,当在开发工具中将鼠标悬停在它们上方时,它显示高度和宽度为 0。我试图让线条连接到元素中的标记。

【问题讨论】:

  • 你没有展示你是如何创建线条或 元素的。

标签: javascript svg


【解决方案1】:

在本例中,我在所有元素上使用相对/绝对位置。我不知道这是否适合您的解决方案,但该示例的核心是 SVG 文档位于所有框的背景中。因此,所有的行都可以放在一个 SVG 文档中。

也许你的线条没有显示的原因是它们错过了笔画宽度或者你的 SVG 元素没有宽度和高度。

let chart = document.querySelector('#chart');
let poschart = chart.getBoundingClientRect();

let line = chart.querySelector('svg line');
let boxs = chart.querySelectorAll('div.box');

let pos1 = boxs[0].getBoundingClientRect();
line.setAttribute('x1', pos1.x+pos1.width/2-poschart.x);
line.setAttribute('y1', pos1.y+pos1.height/2-poschart.y);

let pos2 = boxs[1].getBoundingClientRect();
line.setAttribute('x2', pos2.x+pos2.width/2-poschart.x);
line.setAttribute('y2', pos2.y+pos2.height/2-poschart.y);
#chart {
  position: relative;
  width: 400px;
  height: 300px;
  margin: 10px 20px;
  border: thin solid black;
}

#chart svg {
  position: absolute;
}

.box {
  position: absolute;
  padding: .5em;
  border: thin solid black;
  background-color: white;
}
<div id="chart">
  <svg viewBox="0 0 400 300" width="100%" height="100%">
    <line stroke="black" stroke-width="2"/>
  </svg>
  <div class="box" style="left:50px;top:180px">Box 1</div>
  <div class="box" style="left:310px;top:100px">Box 2</div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2017-12-27
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多