简体   繁体   English

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

[英]Change background color of input field using JS

I'm trying to change background color of an input field when focusing in JS, when its not in focus it should just be a white background color. 我试图在JS中聚焦时更改输入字段的背景色,当它不聚焦时应该只是白色背景色。

I've tried this code, but get an error on it, so I'm not sure what i'm doing wrong. 我已经试过了这段代码,但是遇到了错误,所以我不确定自己在做什么错。

  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> 

There are a few issues in your code : 您的代码中存在一些问题:

  • your handler function declares an obj parameter as the first parameter. 您的处理程序函数将obj参数声明为第一个参数。 When an event is fired, the first element declared in the handler function is a reference to the event object. 触发事件时,在处理函数中声明的第一个元素是对事件对象的引用。
  • you're trying to react to blur or focus , but you're using onclick on your HTML tag. 您试图对blurfocus做出反应,但您在HTML标签上使用了onclick
  • to change your element's background color, you need to modify its style object and, in this style object, the backgroundColor property (the JavaScript equivalent of the background-color CSS property). 要更改元素的背景颜色,您需要修改其style对象,并在此style对象中修改backgroundColor属性(JavaScript等效于background-color CSS属性)。

Here's a solution involving addEventListener function. 这是涉及addEventListener函数的解决方案。 It allows you to attach the same listener to both events : blur and focus . 它使您可以将相同的侦听器附加到两个事件: 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> 

Because your function as parameter so when you call onclick="navn()" without params it can't work 因为您的函数是参数,所以当您在不带参数的情况下调用onclick =“ navn()”时,它将无法正常工作

call it like this : 这样称呼它:

  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