2

我正在制作一个网络应用程序,用户必须在其中输入几个必填文本字段。为了通知用户这一点,声明他/她必须输入所有粉红色的文本字段。我通过这个给了他们粉红色的背景:(注意我正在使用 jQuery UI 微调器小部件)

$('input[type="text"]').spinner({min: 0}).css("background-color", "pink");

我想要做的是当用户在字段中键入时将背景颜色更改为白色。我这样做了:

$('input[type="text"]').keyup(function () {
    if ($(this).val().length !== 0) {
        $(this).css("background-color", "white");
    } else{
        $(this).css("background-color", "pink");
    }
});

这很好用,但我也使用微调器(和滑块)来更改文本字段的值。为此,我输入了这个:

$(document).click(function () {
    if ($('input[type="text"]').val().length !== 0) {
        $('input[type="text"]').css("background-color", "white");
    } else{
        $('input[type="text"]').css("background-color", "pink");
    }
});

正如你可以想象的那样,这不起作用。如果一个文本字段中包含文本,则单击文档后所有文本字段都会变为白色。我无法指定我想以此为目标的文本输入。然后我尝试了一个 .change() jQuery 函数:

$('input[type="text"]').change(function () {
    if ($(this).val().length !== 0) {
        $(this).css("background-color", "white");
    } else{
        $(this).css("background-color", "pink");
    }
});

但是,这仅在用户单击字段外之后才有效,并且当通过微调器或滑块更改值时它什么也不做。有什么建议么?PS:我知道这有点啰嗦,但我想提供尽可能多的信息。

4

1 回答 1

3

在现代浏览器上,请oninput改用:{也添加了其他浏览器支持}

$('input[type="text"]').on('input DOMAttrModified paste change',function () {
    if ($(this).val().length !== 0) {
        $(this).css("background-color", "white");
    } else{
        $(this).css("background-color", "pink");
    }
});
于 2013-05-06T19:32:32.743 回答