【问题标题】:change input background color if its empty如果输入背景颜色为空,则更改输入背景颜色
【发布时间】:2021-03-07 22:29:06
【问题描述】:

我的问题是,当我点击输入后留空时,我想让输入的背景变为红色。

这是我的 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。所以希望这对我来说不会太复杂。

【问题讨论】:

    标签: javascript html input background-color


    【解决方案1】:

    这是一个工作示例。注意使用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>

    【讨论】:

      【解决方案2】:

      您必须使用 onblur() 事件将焦点从输入框中捕获并检查字段值。

      HTML:

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

      JAVASCRIPT:

      要获取字段值,您需要编写 field.value 而不是 field

      function emptyField(x) {
          var field = document.getElementById(x);
          
          if(field.value !== ""){
              field.style.backgroundColor = "white";
          }
          else {
              field.style.backgroundColor = "red";
          }}
      

      【讨论】:

        猜你喜欢
        • 2021-02-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-06
        • 2014-07-17
        • 2011-11-05
        • 2013-12-07
        • 1970-01-01
        相关资源
        最近更新 更多