You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular应用如何实现单字符分隔高亮的证件号码输入框设计

Angular分隔式字符输入框实现方案

核心实现思路

  • 采用「视觉伪装」方案规避原生输入框样式改造的兼容性问题:底层隐藏一个透明的原生input承接用户输入、光标控制、焦点事件等原生能力,上层用一组独立样式的格子渲染分隔的单字符和高亮状态
  • 上层格子和底层input做像素级对齐,确保用户点击格子区域时自动聚焦到输入框,光标位置和当前激活的格子位置一一对应
  • 输入内容自动处理:监听input的输入事件,把输入值拆成单字符数组逐个绑定到上层格子,可根据证件号规则自动过滤无效字符,超过最大长度时自动截断

关键代码片段示例

组件模板

<div class="input-wrapper">
  <!-- 上层显示用字符格子 -->
  <div class="char-box" *ngFor="let char of charList; let i = index" [class.active]="currentCursorPos === i">
    {{ char || '' }}
  </div>
  <!-- 底层隐藏的原生输入框 -->
  <input 
    #idInput 
    type="text" 
    maxlength="18" 
    [formControl]="idCardControl"
    class="hidden-input"
    (input)="updateCharList()"
    (click)="updateCursorPos()"
    (keyup)="updateCursorPos()"
  >
</div>

核心样式

.input-wrapper {
  position: relative;
  display: flex;
  gap: 8px;
}
.char-box {
  width: 40px;
  height: 48px;
  border: 2px solid #eee;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  transition: all 0.2s;
}
/* 当前输入位高亮样式 */
.char-box.active {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}
.hidden-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  /* 隐藏原生光标避免和上层高亮冲突 */
  caret-color: transparent;
}

逻辑控制代码

import { Component, ViewChild, ElementRef } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-id-card-input',
  templateUrl: './id-card-input.component.html',
  styleUrls: ['./id-card-input.component.css']
})
export class IdCardInputComponent {
  @ViewChild('idInput') idInput!: ElementRef<HTMLInputElement>;
  idCardControl = new FormControl('');
  // 按证件号最大长度初始化字符数组
  charList: (string | null)[] = new Array(18).fill(null);
  currentCursorPos = 0;

  updateCharList() {
    const value = this.idCardControl.value || '';
    // 把输入值拆分填充到字符数组,空位补null
    this.charList = value.split('').concat(new Array(18 - value.length).fill(null));
    this.updateCursorPos();
  }

  updateCursorPos() {
    // 同步原生输入框的光标位置到上层高亮逻辑
    this.currentCursorPos = this.idInput.nativeElement.selectionStart || 0;
  }
}

优化建议

  • 输入限制:监听keydown事件,阻止非证件号允许的字符输入,减少无效内容处理逻辑
  • 粘贴适配:监听paste事件,自动过滤粘贴内容中的无效字符后填充到输入框,适配批量输入场景
  • 交互优化:用户点击上层任意格子时,自动把原生输入框的光标移到对应位置,实现点哪输哪的效果
  • 校验联动:如果证件号格式校验不通过,可以给所有格子添加错误状态样式,比如边框变红
  • 无障碍适配:给底层input添加对应的aria属性,保证读屏软件可以正常识别输入框用途

内容的提问来源于stack exchange,提问作者Yahav Azulay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 15:06:04