从一个元素到另一个元素绘制一条线

fac*_*m42 0 html javascript jquery dom shapes

我想画一条可以设置样式的线,从一个<td>元素的中心位置开始,到另一个<td>元素的中心位置结束。


我已经尝试过使用jQuery Connections 插件,但它连接元素的边缘,而不是中心位置。

这个插件的工作原理如下:

$('#start').connections({
  to: '#end',
  'class': 'related'
});
Run Code Online (Sandbox Code Playgroud)

我希望它以同样的方式工作。(或类似的方式)


另外,当我使用jQuery Connections 插件时,连接线显然不会出现。

fac*_*m42 6

经过很长一段时间,我终于找到了解决办法。使用getBoundingClientRect()这两个元素,然后创建一个 SVG 线条元素。SVG 固定在窗口的左上角,可以使用 进行单击pointer-events: none;

var b1 = document.getElementById('btn1').getBoundingClientRect();
var b2 = document.getElementById('btn2').getBoundingClientRect();
var newLine = document.createElementNS('http://www.w3.org/2000/svg', 'line');
newLine.setAttribute('id', 'line1');
newLine.setAttribute('x1', b1.left + b1.width / 2);
newLine.setAttribute('y1', b1.top + b1.height / 2);
newLine.setAttribute('x2', b2.left + b2.width / 2);
newLine.setAttribute('y2', b2.top + b2.height / 2);
newLine.setAttribute('style', 'stroke: black; stroke-width: 2;');
document.getElementById("fullsvg").append(newLine);
Run Code Online (Sandbox Code Playgroud)
#btn1 {
  margin-left: 50px;
  margin-bottom: 5px;
}

#btn2 {
  margin-left: 150px;
}

#fullsvg {
  left: 0px;
  top: 0px;
  position: fixed;
  margin: 0;
  pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)
<input type="button" id="btn1" class="btn" value="button1"><br>
<input type="button" id="btn2" class="btn" value="button2">
<svg id="fullsvg"></svg>
Run Code Online (Sandbox Code Playgroud)