需要脚本通过输入更改div背景

时间:2012-04-09 13:51:34

标签: jquery input background-color

当我返回并删除输入字段为空白的数据时,背景不会恢复为原始颜色,除非我输入“0”。

我需要DIV的背景颜色在空白时恢复原来的颜色。

我做错了什么?

<script>
$(document).ready(function() {

    $("#id").keypress(function() {
        if ($("#id").val().length > 0) $("#in").css("background-color", "red");
        else {
            if ($("#id").val().length == 0) $("#in").css("background-color", "grey");
        }
    });

});​
</script>

5 个答案:

答案 0 :(得分:3)

问题是因为您正在使用在执行密钥操作之前调用的keypress。如果您使用keyup,则可以使用:

$("#id").keyup(function() {
    if ($(this).val().length > 0) {
        $("#in").css("background-color", "red");
    }
    else {
        $("#in").css("background-color", "grey");
    }
});

另外,正如@ mblase75指出的那样,你不需要在else条件下测试值的length

Example fiddle

如果您想进一步简化此代码,可以使用带有.val().length的三元语句作为条件,因为正整数将等于true:

$("#id").keyup(function() {
    $(this).css("background-color", $(this).val().length ? "red" : "grey");
});

答案 1 :(得分:2)

您可能希望使用keyup来说明刚刚输入的字符:

$(function(){
    $("#id").keyup(function() {
        $("#in").css("background-color", $(this).val().length > 0 ? "red" : "grey");
     });
 });​

这是一个jsFiddle来演示。

答案 2 :(得分:0)

这个应该有用......

<script>

$(document).ready(function() {

    $("#id").keyup(function() {
        if($("#id").val().length > 0) {
           $("#in").css("background-color", "red");
        }
        else {
           $("#in").css("background-color", "grey");
        }
    });
});​

</script>

答案 3 :(得分:0)

在您的情况下,'keypress'事件在input.val()。length更改之前调用。 并且你的代码运行选择器后退五次,输入一个。

看看这段代码,它运行正常:

HTML:

<input id="id" type="text" autocomplete="off">
<div class="in"></div>​​​

的CSS:

.in {width:200px; height:20px; background-color:#grey;}
.in-red {background-color:red;}

JS:

$(function(){
    var $in = $('.in');
    $('#id').on('keyup', function(){
        $this = $(this);
        if ($this.val().length > 0) {
            $in.addClass('in-red');
        } else {
            $in.removeClass('in-red');
        }
    });
});​

您可以在http://jsfiddle.net/Qhkev/1/

上进行测试

答案 4 :(得分:-2)

使用keyup

<script>
$(document).ready(function(){

$("#id").keyup(function() {
    if($("#id").val().length > 0) $("#in").css("background-color", "red");
  else {
    if($("#id").val().length == 0) $("#in").css("background-color", "grey");
 }

 });
 });
 </script>