字段输入后的颜色变化 - CSS

时间:2016-07-12 16:29:52

标签: html css

是否有任何css属性可用于突出显示所有填充的字段?就像我们一样,关注焦点css属性。



input[type="text"] {
  background-color: white;
}
input[type="text"]:focus {
  background-color: red;
}

<input type="text">
&#13;
&#13;
&#13;

当场中有东西时,我想让场背景颜色为绿色。这可以通过CSS吗?如果不是CSS,还有其他方法吗?

2 个答案:

答案 0 :(得分:0)

当然,您可以使用javascript实现此目的。

在焦点转移到任何一个keyup字段后,下面的脚本会侦听<input>

然后会检查相应的<input>字段是否为空。

如果不是,则会将<input>字段的背景更改为绿色。

&#13;
&#13;
var inputs = document.querySelectorAll('input[type="text"]');

function detectContent() {
    if (this.value !== '') {
        this.style.backgroundColor = 'green';
        this.style.color = 'white';
    } else {
        this.style.backgroundColor = 'white';
        this.style.color = 'black';
    }
}


for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    input.addEventListener('keyup', detectContent, false);
}
&#13;
<input type="text" />

<input type="text" />

<input type="text" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个......

$(document).ready(function() {
  $(':input').on('input', function() {
    if (this.value.length > 0) {
      $(this).css('background-color', 'green');
    } else {
      $(this).css('background-color', '');
    }
  });
});
input[type="text"] {
  background-color: white;
  color: #fff;
}
input[type="text"]:focus {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<input type="text">