简体   繁体   English

我可以根据文本的值更改类吗?

[英]Can I change the class based on the value of the text?

I'm okay with JS but I'm not the greatest.我对 JS 没问题,但我不是最伟大的。 So Would it be possible to change the class of an input if the input is less than 3?那么,如果输入小于 3,是否可以更改输入的类别? Simple question, would it be possible for someone to leave a block of code that I can mess with?一个简单的问题,有人可以留下我可以弄乱的代码块吗?

Thanks谢谢

you have to use ascii method charAt(0) :你必须使用 ascii 方法 charAt(0) :

 const inText = document.getElementById('in-text') inText.oninput=()=> { if (inText.value.length=1) { inText.className = (inText.value.charAt(0) < '3'.charAt(0)) ? 'green' : 'blue' } }
 #in-text { color: white; font-size:2em; font-weight: bold; } .blue { background-color: darkblue;} .green { background-color:darkgreen;}
 <input type='text' id='in-text' size="1" value="$" class="green">

Yes, you can do something like this.是的,你可以做这样的事情。

Let's say you have the input field with type as "number" and some id.假设您的输入字段的类型为“数字”和一些 id。

<input type="number" id="numberInput" onkeyup="myFunction()" />

Then the js will be like this然后js就会变成这样

function myFunction() {
   const input = document.getElementById("numberInput");
   if(input.value <= 3){
      input.classList.add("myClass");
   }
}

This will fire an event on each keyup event on the input field.这将在输入字段上的每个 keyup 事件上触发一个事件。 It will add a new class if value is less than three.如果值小于三,它将添加一个新类。
You can also fire the event on change(onchange="myFunction()") but the event will be fired only when user clicks away from the input field.您也可以在 change(onchange="myFunction()") 上触发事件,但只有当用户点击离开输入字段时才会触发该事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM