我想画一条可以设置样式的线,从 <td>
的中心位置开始元素,并在另一个 <td>
的中心位置结束元素。
我已经尝试过使用 jQuery Connections plugin ,但它连接元素的边缘,而不是中心位置。
This plugin就像这样简单地工作:
$('#start').connections({
to: '#end',
'class': 'related'
});
我希望它能以同样的方式工作。 (或类似的方式)
<小时/>当我使用 jQuery Connections plugin 时也是如此,连接线显然没有出现。
最佳答案
折腾了好久,终于找到解决办法了。在两个元素上使用 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);
#btn1 {
margin-left: 50px;
margin-bottom: 5px;
}
#btn2 {
margin-left: 150px;
}
#fullsvg {
left: 0px;
top: 0px;
position: fixed;
margin: 0;
pointer-events: none;
}
<input type="button" id="btn1" class="btn" value="button1"><br>
<input type="button" id="btn2" class="btn" value="button2">
<svg id="fullsvg"></svg>
关于javascript - 从一个元素到另一个元素绘制一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56722754/