Html让两个Dom进行连线 , 可以自定义连接的位置
function getXy(dom, pos) {
var obj = {x : 0, y : 0};
if(pos == 'button') {
obj.x = dom.offsetLeft + dom.offsetWidth / 2;
obj.y = dom.offsetTop + dom.offsetHeight;
}else if(pos == 'left') {
obj.x = dom.offsetLeft;
obj.y = dom.offsetTop + dom.offsetHeight / 2;
}else if(pos == 'right') {
obj.x = dom.offsetLeft + dom.offsetWidth;
obj.y = dom.offsetTop + dom.offsetHeight / 2;
}else if(pos == 'top') {
obj.x = dom.offsetLeft + dom.offsetWidth / 2;
obj.y = dom.offsetTop;
}
return obj;
}
function connectEdges(id1, id2, color = 'red', width = '0.5' , pos1 = 'right', pos2 = 'left') {
const dom1 = document.getElementById(id1);
const dom2 = document.getElementById(id2);
const svg = document.getElementById('svg-container');
var objXy1 = getXy(dom1, pos1);
var objXy2 = getXy(dom2, pos2);
// 创建SVG线条
const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', objXy1.x);
line.setAttribute('y1', objXy1.y);
line.setAttribute('x2', objXy2.x);
line.setAttribute('y2', objXy2.y);
line.setAttribute('stroke', color); // 线条颜色
line.setAttribute('stroke-width', width); // 线条宽度
// 将线条添加到SVG容器中
svg.appendChild(line);
}
// 这是我自己的业务代码
for(var i = 0 ; i < data.length ; i++) {
var obj = data[i];
if(obj.source != obj.target){
if(obj.target.indexOf('配偶') != -1) {
connectEdges(obj.source, obj.target, 'red', 2, 'right', 'left');
}else{
connectEdges(obj.source, obj.target, 'blue', 0.5, 'button', 'top');
}
}
}
原文地址:https://blog.csdn.net/dongyan3595/article/details/143852462
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!