更改输入css的值的长度函数

Change input css in function of the length of its value

本文关键字:函数 输入 css      更新时间:2023-09-26

如何在JS中生成依赖于html输入字段中字符数的if语句?例如,如果输入字段中的值大于0,则该字段的css属性将发生更改。

这取决于您是否希望在页面加载或输入字段发生更改时进行检查。在页面加载检查@gurvinder372回答,否则您可以在输入字段上检查onkeyup

document.getElementById('input').onkeyup = function(){
     if(this.value.length > 0) {
     		this.style.background = 'red';
     } else {
     		this.style.background = 'green';
     }
}
<input type="text" id="input">

类似的东西?

<input type="text" id="text1">

js编码if条件作为

document.onload = function(){
  var val = document.getElementById("text1").value;
  var characterCount = 10;
  if ( val.length > characterCount )
  {
    //Now the character count is greater than 10
    document.getElementById("text1").style.backgroundColor = "#f00";
  }
};

为了完成答案列表,现在有一个答案在输入失去焦点时评估值。

function inputChange(value) {
	window.txt.style.color = value > 3 ? 'red' : 'blue';
}
<input id="txt" onchange="inputChange(this.value)" />