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

标签 javascript jquery html dom shapes

我想画一条可以设置样式的线,从 <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/

相关文章:

html - 如何缩小 div 以适应自动换行的文本

php - 我可以在 HTML5 中创建自定义 HTML 标签吗?

javascript - 在 document.ready 到 window.load 期间在特定的 div 上设置加载器

javascript - Breeze.js 和 Tasypie : Handling non OData API

javascript - JQuery 变量通配符或正则表达式

javascript - 更改媒体大小:thumbnail on Blogger RSS Feed

javascript - 使用 jquery 重新映射键盘

jquery - 使用 jQuery 和 ajax 进行拖放

JavaScript 函数数据处理

javascript - jquery:如何防止导航(链接/提交)?