本文介绍使用 angularjs 实现上下两排字段(如 5+5)之间通过鼠标点击配对并动态绘制 svg 连线的完整方案,支持多次点击建立多条连接线,并自动计算元素位置、避免硬编码坐标。
在 AngularJS 应用中,实现两个字段(例如上排和下排的可点击区域)之间的可视化连线,核心在于:捕获点击事件 → 获取 DOM 元素绝对位置 → 记录起始/终止坐标 → 动态渲染 SVG 线段。以下是一个结构清晰、可复用的实现方案。
,每个字段赋予唯一 ID(如 1_1, 2_3),便于后续 DOM 查询;app.controller("MainCtrl", function ($scope) {
$scope.top_span = [{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "5"}];
$scope.bottom_span = [{name: "1"}, {name: "2"}, {name: "3"}, {name: "4"}, {name: "5"}];
$scope.lines = []; // 存储所有已创建的连线对象
$scope.unline = {}; // 临时存储当前未完成的连线(from/to)
$scope.getPosTop = function (index) {
const el = document.getElementById(`1_${index}`);
el.style.transform = "scale(0.8)";
const rect = el.getBoundingClientRect();
if ($scope.unline.from) {
// 已有起点,本次点击设为终点 → 完成连线
$scope.unline.to = { x: rect.left + 15, y: rect.top + 30 };
$scope.lines.push(angular.copy($scope.unline));
$scope.unline = {};
} else {
// 首次点击,设为起点
$scope.unline.from = { x: rect.left + 15, y: rect.top + 30 };
}
};
$scope.getPosBottom = function (index) {
const el = document.getElementById(`2_${index}`);
el.style.transform = "scale(0.8)";
const rect = el.getBoundingClientRect();
if ($scope.unline.from) {
// 补全终点,立即提交连线
$scope.unline.to = { x: rect.left + 15, y: rect.top };
$scope.lines.push(angular.copy($scope.unline));
$scope.unline = {};
} else {
// 单独点击下排 → 设为起点(允许反向连线)
$scope.unline.from = { x: rect.left + 15, y: rect.top };
}
};
});⚠️ 注意:使用 getBoundingClientRect() 替代 offsetLeft/offsetTop 更可靠,它返回相对于视口的位置,不受父容器 position 影响,适配滚动与响应式布局。
{{c.name}}
{{c.name}}
.parent_span, .parent_span_2 {
display: flex;
justify-content: space-between;
margin: 40px 0;
}
.top_span, .bottom_span {
display: flex;
flex-direction: column;
align-items: center;
}
.line {
position: fixed;
top: 0; left: 0;
width: 100%; height: 100%;
pointer-events: none; /* 确保不拦截下方点击 */
z-index: -1;
}
.line svg {
width: 100%; height: 100%;
}该方案轻量、无第三方依赖,完全基于原生 AngularJS 数据绑定与 DOM 操作,适合快速集成到传统 AngularJS 项目中。