首页 > 解决方案 > 如果输入背景颜色为空,则更改输入背景颜色

问题描述

我的问题是,当我在单击后留空时,我想将输入的背景设为红色。

这是我的 HTML:

<div id="name">
<label>Name<sup></sup></label> <br>
    <input id="first" style="font-size:11pt;" type="text" name="name" placeholder="First Name" onChange='emptyField("first")'/>
    <input id="last" style="font-size:11pt;" type="text" name="name" placeholder="Last Name" onChange='emptyField("last")'/> 
</div>

这是我的javascript程序:

function emptyField(x) {
var field = document.getElementById(x);

if(field !== ""){
    field.style.backgroundColor = "white";
}
else {
    field.style.backgroundColor = "red";
}}

顺便提一下,我刚刚开始学习 HTML、CSS、JS 和 PHP。所以希望它对我来说不会太复杂理解。

标签: javascripthtmlinputbackground-color

解决方案


这是一个工作示例。注意focusout事件的使用,而不是change

document.querySelectorAll('input[type="text"]').forEach(e => {
  e.addEventListener('focusout', setInputBackground)
});

function setInputBackground() {
  this.style.backgroundColor = !!this.value ? "white" : "red";
}
<div id="name">
  <label>Name<sup></sup></label> <br>
  <input id="firstname" style="font-size:11pt;" type="text" name="firstname" placeholder="First Name" />
  <input id="lastname" style="font-size:11pt;" type="text" name="lastname" placeholder="Last Name" />
</div>


推荐阅读