繁体   English   中英

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

[英]Change background color of input field using 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> 

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

  • 您的处理程序函数将obj参数声明为第一个参数。 触发事件时,在处理函数中声明的第一个元素是对事件对象的引用。
  • 您试图对blurfocus做出反应,但您在HTML标签上使用了onclick
  • 要更改元素的背景颜色,您需要修改其style对象,并在此style对象中修改backgroundColor属性(JavaScript等效于background-color 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> 

因为您的函数是参数,所以当您在不带参数的情况下调用onclick =“ navn()”时,它将无法正常工作

这样称呼它:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM