使用JS更改输入字段的背景颜色

时间:2018-05-18 12:52:00

标签: javascript html input background-color

当我在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>

2 个答案:

答案 0 :(得分:4)

您的代码中存在一些问题:

  • 您的处理函数声明obj参数作为第一个参数。触发事件时,处理函数中声明的第一个元素是对事件对象的引用。
  • 您尝试对blurfocus做出反应,但您在HTML代码上使用onclick
  • 要更改元素的背景颜色,您需要修改其style对象,并在此style对象中修改backgroundColor属性(等同于background-color的JavaScript CSS属性)。

这是一个涉及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>

答案 1 :(得分:0)

因为你的函数作为参数所以当你调用onclick =“navn()”时没有参数它就无法工作

这样称呼:

  onblur="blur(this)"  onfocus="focus(this)"

  function blur(obj) {
                obj.style.backgroundColor == "white";
        }
  function focus(obj) {
                obj.style.backgroundColor = "yellow";
        }
相关问题