根据PHP中的输入更改输入背景颜色


Changing input background color depending on the input in PHP

我在输入字段的背景颜色变化方面遇到了麻烦。如果它是空的,或者已经在使用,或者我定义的其他规则,背景颜色应该改变。只是我需要一个简单形式的例子,如:

<form name="login" action="" method="post">
Username: <input type="text" name="username"><br />
<input type="submit" name="submit" value="Submit">
</form>

我想使用PHP和CSS代码来做到这一点。请随意使用div类和其他东西。

谢谢

您可以使用CSS3属性选择器完成此操作。例如,如果输入为空,则希望背景为红色,否则为绿色。

input { background: green; }
input[value=""] { background: red; }

注意CSS3属性选择器不完全兼容IE8及更低版本。所有其他现代浏览器都支持。

如果你想让它动态更新(例如:当用户在输入框中输入内容时从红色变为绿色),您必须使用Javascript。

我给你写了一个小例子

css

.placeholder {color:#aaa;}
input[type=text],
input[type=password] {
    background:#eee;
}
input[type=text]:focus,
input[type=password]:focus {
    background:#fff;
}

js

$("#username").focus(function(){
    if($(this).val() == "Benutzername")
    {
        $(this).val("");
        $(this).removeClass('placeholder');
    }
});
$("#username").blur(function(){
    if($(this).val() == "")
    {
        $(this).val("Benutzername");
        $(this).addClass('placeholder');
    }
});
$("#password").focus(function(){
    if($(this).val() == "Passwort")
    {
        $(this).val("");
        $(this).prop("type", "password");
        $(this).removeClass('placeholder');
    }
});
$("#password").blur(function(){
    if($(this).val() == "")
    {
        $(this).val("Passwort");
        $(this).prop("type", "text");
        $(this).addClass('placeholder');
    }
});

html

<input id="username" type="text" class="placeholder" value="Benutzername" /><br />
<input id="password" type="text" class="placeholder" value="Passwort" />

在JSFiddle中查看http://jsfiddle.net/hk8k4vew/