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

使用JS实现输入框焦点切换背景色的问题排查

解决输入框焦点背景色切换的代码问题

我来帮你排查代码里的问题,让输入框在获取焦点时变黄、失焦时变白的功能正常工作~

你的代码存在两个主要问题:

  • 未关联目标元素的样式对象:函数里直接使用style.background是无效的,因为style没有指向触发事件的输入框。你需要通过传入的obj参数(也就是当前输入框元素)来访问它的样式,即obj.style.background。
  • 事件绑定错误:你只给输入框绑定了onclick事件,但我们需要监听的是focus(获取焦点)和blur(失去焦点)事件,而且调用函数时没有传递必要的this(当前元素)和event(事件对象)参数。

修正后的代码(内联事件写法)

JavaScript代码:

function navn(obj, evt) {
  if (evt.type === "focus") {
    obj.style.background = "yellow";
  } else if (evt.type === "blur") {
    obj.style.background = "white";
  }
}

HTML代码:

<form>
  <fieldset>
    <legend>Personlige oplysninger</legend>
    <div>
      <label for="navn">Udfyld dit fornavn:</label>
      <input 
        type="text" 
        name="navn" 
        class="navn" 
        id="navn" 
        value="" 
        onfocus="navn(this, event)" 
        onblur="navn(this, event)" 
        placeholder="Dit fornavn" 
      />*
      <span id="obsnavn" class="alert"></span>
    </div>
    <input type="button" value="Send" id="send" />
  </fieldset>
</form>

更推荐的现代写法(分离JS和HTML)

内联事件虽然简单,但不利于代码维护,推荐使用addEventListener来绑定事件,把JS和HTML完全分离:

JavaScript代码:

// 获取目标输入框元素
const navnInput = document.getElementById('navn');

// 绑定获取焦点事件
navnInput.addEventListener('focus', function() {
  this.style.background = 'yellow';
});

// 绑定失去焦点事件
navnInput.addEventListener('blur', function() {
  this.style.background = 'white';
});

HTML代码(去掉内联事件):

<form>
  <fieldset>
    <legend>Personlige oplysninger</legend>
    <div>
      <label for="navn">Udfyld dit fornavn:</label>
      <input 
        type="text" 
        name="navn" 
        class="navn" 
        id="navn" 
        value="" 
        placeholder="Dit fornavn" 
      />*
      <span id="obsnavn" class="alert"></span>
    </div>
    <input type="button" value="Send" id="send" />
  </fieldset>
</form>

这样修改后,输入框就能正常在焦点切换时改变背景色啦~

内容的提问来源于stack exchange,提问作者Ida Isabella Thor-Rasmussen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:29:45