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

JavaScript实时监听输入长度:密码框背景色动态切换需求

密码输入框实时长度验证样式实现

直接上可运行的代码,核心逻辑是监听输入框的实时输入事件,根据密码长度切换背景色:

HTML 结构

<input type="password" id="passwordInput" placeholder="请输入密码(至少8位)">

JavaScript 逻辑

const passwordInput = document.getElementById('passwordInput');

// 监听输入事件,实时触发验证
passwordInput.addEventListener('input', function() {
  const passwordLength = this.value.length;
  // 根据长度设置背景色
  if (passwordLength < 8) {
    this.style.backgroundColor = '#ffcccc'; // 浅红色
  } else {
    this.style.backgroundColor = '#ccffcc'; // 浅绿色
  }
});

关键点说明

  • 用input事件而不是change事件:input会在用户每输入/删除一个字符时立刻触发,实现实时反馈;change只有输入框失去焦点时才触发,不符合实时验证的需求。
  • 选浅红/浅绿是因为比纯红纯绿更柔和,用户体验更好,你也可以换成自己偏好的hex或rgb颜色值。
  • 初始状态下输入框保持默认背景样式,只有开始输入后才会根据长度切换颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:54:31