如何在 AngularJS 中实现上下两组字段的点击连线功能

本文介绍使用 angularjs 实现上下两排字段(如 5+5)之间通过鼠标点击配对并动态绘制 svg 连线的完整方案,支持多次点击建立多条连接线,并自动计算元素位置、避免硬编码坐标。

在 AngularJS 应用中,实现两个字段(例如上排和下排的可点击区域)之间的可视化连线,核心在于:捕获点击事件 → 获取 DOM 元素绝对位置 → 记录起始/终止坐标 → 动态渲染 SVG 线段。以下是一个结构清晰、可复用的实现方案。

✅ 核心逻辑说明

  • 使用 ng-repeat 渲染上下两组字段(如 top_span 和 bottom_span),每个字段赋予唯一 ID(如 1_1, 2_3),便于后续 DOM 查询;
  • 点击上排字段时,调用 getPosTop($index),获取其左上角偏移量,并暂存为连线起点(unline.from);
  • 点击下排字段时,调用 getPosBottom($index),获取其位置作为终点(unline.to),随后将该线段推入 lines 数组,并清空临时对象;
  • 所有连线统一由 内的 元素渲染,通过 ng-repeat="line in lines" 绑定,利用 x1/y1/x2/y2 动态设置端点坐标;
  • 为提升交互反馈,点击后对目标元素应用缩放动画(transform: scale(0.8)),增强用户感知。

? 关键代码片段(Controller)

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 影响,适配滚动与响应式布局。

? HTML 与 SVG 渲染结构



  
    
      ...
    
    {{c.name}}
  




  
    
      ...
    
    {{c.name}}
  




  
    
  

? CSS 布局建议

.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%;
}

✅ 扩展提示

  • 若需支持「取消连线」,可在 lines 中为每条线添加唯一 ID,并提供 removeLine(id) 方法;
  • 如字段数量动态变化,建议将 top_span / bottom_span 改为 $scope.config = { topCount: 10, bottomCount: 10 },配合 ng-repeat="i in getNumberArray(topCount) track by $index";
  • 生产环境建议封装为自定义指令(如 field-linker),提升复用性与隔离性。

该方案轻量、无第三方依赖,完全基于原生 AngularJS 数据绑定与 DOM 操作,适合快速集成到传统 AngularJS 项目中。