簡體   English   中英

如果為空,則更改輸入背景顏色

[英]change input background color if its empty

我的問題是,當我點擊它后將其留空時,我想讓我的輸入背景變為紅色。

這是我的 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。 所以希望它對我來說理解起來不會太復雜。

您必須使用 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>

爪哇腳本:

要獲取字段值,您必須編寫field.value而不是field

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM