首页 > 解决方案 > 使用JS更改输入字段的背景颜色

问题描述

我试图在 JS 中聚焦时更改输入字段的背景颜色,当它没有聚焦时,它应该只是白色背景颜色。

我已经尝试过这段代码,但是得到了一个错误,所以我不确定我做错了什么。

            function navn(obj, evt) {
                if (evt.type == "focus")
                    style.background = "yellow";  //<--what is style?
                else if (evt.type == "blur") {
                    style.background = "white";
                }
            }
 <form>

            <fieldset>
                <legend>Personlige oplysninger</legend>

                <div>
                    <label for="navn">Udfyld dit fornavn:</label>
                    <input type="text" name="navn" class="navn" id="navn" value="" onclick="navn()" placeholder="Dit fornavn" />*
                    <span id="obsnavn" class="alert"></span>
                </div>

                <input type="button" value="Send" id="send" />

            </fieldset>

        </form>

标签: javascripthtmlinputbackground-color

解决方案


您的代码中有几个问题:

  • 您的处理程序函数将参数声明obj为第一个参数。触发事件时,处理函数中声明的第一个元素是对事件对象的引用。
  • 您正在尝试对bluror做出反应focus,但您正在onclickHTML 标记上使用。
  • 要更改元素的背景颜色,您需要修改它的style对象以及该style对象中的backgroundColor属性(background-colorCSS 属性的 JavaScript 等效项)。

这是一个涉及addEventListener功能的解决方案。它允许您将相同的侦听器附加到两个事件:blurfocus

var element = document.getElementById("navn");
element.addEventListener("focus", handler);
element.addEventListener("blur", handler);

function handler(evt) {
    if (evt.type == "focus")
        evt.target.style.backgroundColor = "yellow"; //<--what is style?
    else if (evt.type == "blur") {
        evt.target.style.backgroundColor = "white";
    }
}
<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>


推荐阅读