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

输入框有内容时自动改变背景色的实现方案:支持jQuery、JavaScript或CSS吗?

实现Kahoot!风格的输入框背景色随输入变化效果

嘿,这个Kahoot的输入框效果确实挺讨喜的!当然可以用CSS、原生JavaScript或者jQuery来实现,我给你整理了几种不同方案,你可以根据自己的项目情况来选:

CSS 实现方案(最简单无JS)

如果只是需要「输入有内容时切换背景色」的基础效果,用CSS的:placeholder-shown伪类就能搞定,完全不需要写JS。核心逻辑是:当输入框的占位符显示(输入为空)时用默认样式,占位符隐藏(有内容)时切换背景色。

/* 输入为空时的默认样式 */
.kahoot-input {
  padding: 12px 16px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  background-color: #ffffff;
  transition: all 0.3s ease; /* 加上过渡动画,切换更丝滑 */
  font-size: 16px;
}

/* 输入有内容时的样式 */
.kahoot-input:not(:placeholder-shown) {
  background-color: #f0f9ff; /* 换成你想要的Kahoot风格颜色 */
  border-color: #3b82f6;
}
<input type="text" class="kahoot-input" placeholder="输入内容试试...">

原生JavaScript 实现方案(灵活可控)

如果需要更复杂的逻辑(比如根据输入字符数、内容类型动态改变颜色),原生JS是更好的选择。我们可以监听输入框的input事件,实时检测输入内容,然后动态修改样式:

<input type="text" id="custom-input" placeholder="输入内容试试..." style="padding:12px 16px; border:2px solid #e0e0e0; border-radius:8px; transition:all 0.3s ease;">
const input = document.getElementById('custom-input');

// 监听输入事件,实时响应
input.addEventListener('input', function() {
  if (this.value.trim().length > 0) {
    // 有内容时的样式
    this.style.backgroundColor = '#f0f9ff';
    this.style.borderColor = '#3b82f6';
  } else {
    // 无内容时恢复默认
    this.style.backgroundColor = '#ffffff';
    this.style.borderColor = '#e0e0e0';
  }
});

jQuery 实现方案(简洁高效)

如果你的项目已经引入了jQuery,写法会更简洁,逻辑和原生JS一致,但代码量更少:

<input type="text" class="jq-input" placeholder="输入内容试试..." style="padding:12px 16px; border:2px solid #e0e0e0; border-radius:8px; transition:all 0.3s ease;">
$('.jq-input').on('input', function() {
  const hasContent = $(this).val().trim() !== '';
  $(this).css({
    'background-color': hasContent ? '#f0f9ff' : '#ffffff',
    'border-color': hasContent ? '#3b82f6' : '#e0e0e0'
  });
});

小技巧

如果你想1:1复刻Kahoot的效果,可以打开浏览器开发者工具(按F12),直接查看他们输入框的CSS样式和绑定的事件,参考他们的颜色值、动画时长等参数,效果会更还原~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:52:42