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

如何使用JavaScript实现输入与data属性匹配时逐字变色功能?

实现方案

原生<input>元素不支持给内部部分字符单独设置颜色,你可以根据需求选择以下两种方案:

方案1:仅修改输入框边框颜色(基于你原有代码改造)

只需要把判断逻辑从「完全匹配」改成「输入内容是目标值的前缀」即可:

let all = document.querySelectorAll('#input_Text')
all.forEach(element => element.addEventListener('input',(e)=>{
    const target = element.getAttribute('data-verb')
    // 用startsWith判断输入内容是不是目标值的前缀
    if(target.startsWith(e.target.value)){
        element.style.border = "5px solid green"
    }else{
        element.style.border = "5px solid red"
    }
}))

方案2:输入字符本身逐字变色

需要用contenteditable元素模拟输入框,实现部分文本染色效果:

HTML示例

<!-- 替换原有input,保留data-verb属性 -->
<div class="mock-input" contenteditable="true" data-verb="word"></div>

CSS示例

.mock-input {
  border: 1px solid #d1d5db;
  padding: 6px 10px;
  width: 280px;
  font-size: 16px;
  line-height: 1.5;
  outline: none;
  min-height: 24px;
}
.match {
  color: #16a34a;
}
.not-match {
  color: #dc2626;
}

JS代码

const mockInputs = document.querySelectorAll('.mock-input')
mockInputs.forEach(el => el.addEventListener('input', handleMockInput))

function handleMockInput(e) {
  const el = e.target
  const targetStr = el.getAttribute('data-verb')
  const inputStr = el.textContent || ''
  let renderHtml = ''

  // 逐字符对比渲染
  for (let i = 0; i < inputStr.length; i++) {
    const isMatch = i < targetStr.length && inputStr.slice(0, i+1) === targetStr.slice(0, i+1)
    renderHtml += `<span class="${isMatch ? 'match' : 'not-match'}">${inputStr[i]}</span>`
  }

  el.innerHTML = renderHtml
  // 光标移到内容末尾,避免输入错位
  const range = document.createRange()
  const selection = window.getSelection()
  range.selectNodeContents(el)
  range.collapse(false)
  selection.removeAllRanges()
  selection.addRange(range)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:57:04