如何在带字符下划线的input输入框中为第3、4位字符添加间距?
问题
需要实现一个带字符下划线的input输入框,要求在输入的6位代码第3个与第4个字符之间添加间距,匹配设计稿样式。现有如下CSS与HTML代码,该如何调整实现需求?
.code-input { display: block; margin: 0; border: none; padding: 0; width: 120px; background: repeating-linear-gradient(90deg, #818181 0, #818181 16px, transparent 16px, transparent 18px, #818181 18px, #818181 34px, transparent 34px, transparent 36px, #818181 36px, #818181 54px, transparent 54px, transparent 62px) 0 100%/ 120px 1px no-repeat; font-family: 'Inter', monospace; font-weight: 300; font-size: 28px; line-height: 24px; } .code-input:focus { outline: none; }
<input class='code-input' maxLength='6' defaultValue='' />
解决方案
要实现这个需求,需要从调整背景下划线样式和格式化输入内容两方面入手,具体修改如下:
1. 调整CSS背景渐变(匹配间距的下划线)
修改背景渐变的分段逻辑,在第3和第4个字符的下划线之间留出额外间距,同时调整输入框宽度容纳这个间距:
.code-input { display: block; margin: 0; border: none; padding: 0 8px 0 0; /* 右侧内边距抵消最后一个字符的额外间距 */ width: 140px; /* 加宽以容纳额外间距 */ /* 调整渐变分段,第3-4位下划线之间增加8px间距 */ background: repeating-linear-gradient(90deg, #818181 0, #818181 16px, transparent 16px, transparent 18px, #818181 18px, #818181 34px, transparent 34px, transparent 42px, #818181 42px, #818181 58px, transparent 58px, transparent 60px, #818181 60px, #818181 76px) 0 100%/ 140px 1px no-repeat; font-family: 'Inter', monospace; font-weight: 300; font-size: 28px; line-height: 24px; letter-spacing: 4px; /* 统一字符间距,保证视觉对齐 */ text-align: left; } .code-input:focus { outline: none; }
2. 添加JavaScript格式化输入内容
通过监听输入事件,自动在第3个字符后插入空格,同时处理删除操作时的光标异常,确保实际有效输入为6位:
<input class='code-input' maxLength='7' defaultValue='' /> <script> const codeInput = document.querySelector('.code-input'); // 格式化输入内容,在第3位后添加空格 codeInput.addEventListener('input', function() { let rawValue = this.value.replace(/\s/g, ''); // 移除所有空格 if (rawValue.length > 3) { rawValue = rawValue.slice(0, 3) + ' ' + rawValue.slice(3, 6); } this.value = rawValue; }); // 处理删除空格时的光标问题 codeInput.addEventListener('keydown', function(e) { if (e.key === 'Backspace' && this.value.charAt(this.selectionStart - 1) === ' ') { e.preventDefault(); this.selectionStart -= 1; this.value = this.value.slice(0, this.selectionStart) + this.value.slice(this.selectionEnd); } }); </script>
关键说明
- 背景渐变调整:把原第3位后的透明段从2px(34px-36px)改成8px(34px-42px),实现下划线之间的间距;
- 字符间距:用
letter-spacing保证每个字符的宽度一致,配合插入的空格实现视觉分隔; - 输入限制:将
maxLength设为7(6位有效字符+1个空格),确保不会输入过多内容; - 光标处理:监听退格键,避免删除空格时光标跳位,提升输入流畅度。
内容的提问来源于stack exchange,提问作者Vlada Melnikova
相关产品推荐
相关产品推荐

