如何实现输入框输入内容时指定字符自动变更颜色?

原生 <input> 标签的输入内容由浏览器原生渲染为纯文本,没有开放针对内容片段单独设置样式的能力,因此无法直接在输入框本体上实现单字符定制颜色的效果。要实现输入时自动为指定字符匹配对应颜色的交互,可通过叠层伪装的输入结构完成,具体实现如下:
核心实现思路
- 搭建完全对齐的两层叠放结构:底层为可视化的高亮展示层(普通div容器),上层为完全透明的真实输入框,两者的字体、字号、内边距、行高、宽度完全一致,让用户感知上是在直接对输入框操作
- 每次输入触发事件时,读取输入框中的纯文本内容,逐字符匹配自定义高亮规则,符合规则的字符包裹带对应颜色的class标签,将处理后的富文本内容渲染到底层展示层
- 做好特殊字符转义处理,避免用户输入带HTML代码的内容导致页面渲染异常
完整可运行代码
HTML 结构
<body> <div class="input-container"> <!-- 底层高亮展示层 --> <div id="highlight-box" class="display-area"></div> <!-- 上层透明真实输入层 --> <input type="text" id="real-input" class="input-area" placeholder="输入试试"> </div> <h1 id="values"><span class="Q">Q</span><span class="W">W</span><span class="R">R</span><span class="T">T</span></h1> </body>
CSS 样式
body { font-family: sans-serif; color: #222; } .input-container { position: relative; width: 420px; margin: 24px 0; border: 1px solid #e5e5e5; border-radius: 6px; } /* 两层共用排版规则,保证文字完全对齐无错位 */ .display-area, .input-area { margin: 0; padding: 10px 14px; font-size: 16px; font-family: sans-serif; line-height: 1.6; box-sizing: border-box; white-space: pre-wrap; word-break: break-all; } .input-area { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; /* 完全透明,仅保留输入交互和光标功能 */ background: transparent; border: none; outline: none; z-index: 2; } .display-area { min-height: 44px; color: #333; background: #fff; } /* 自定义高亮字符的样式 */ .text-green { color: #22c55e; }
JavaScript 逻辑
const realInput = document.getElementById('real-input'); const displayBox = document.getElementById('highlight-box'); // 自定义高亮规则:指定字符匹配对应样式 const highlightConfig = [ { targetChars: ['h','e','l','o'], styleClass: 'text-green' } ]; // 输入事件监听,实时更新高亮展示 realInput.addEventListener('input', function() { const rawText = this.value; let renderContent = ''; // 逐字符匹配规则,同时做特殊字符转义防XSS for (let char of rawText) { let hasMatched = false; for (let rule of highlightConfig) { if (rule.targetChars.includes(char.toLowerCase())) { renderContent += `<span class="${rule.styleClass}">${char}</span>`; hasMatched = true; break; } } if (!hasMatched) { renderContent += char .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>'); } } displayBox.innerHTML = renderContent; }); // 原有逻辑保留 document.addEventListener("input", function() { document.getElementById('values').style.color = "#999"; });
注意事项
- 两层结构的排版属性必须完全一致,否则会出现文字错位、光标和输入位置不匹配的问题
- 处理文本渲染时必须做特殊字符转义,否则用户输入带HTML标签的内容会破坏页面正常结构
- 如果需要支持多行输入,只需将透明层的input替换为textarea,保持相同的排版对齐规则即可
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

