I am trying to create an input text field, and when values like 1, 2, 3 are typed in the text field the background color of the text field will change to Red, Yellow, and Green, respectively. I have find some clue here but unable to get my desired output (Conditional format). Not that great in js, so any help will be highly appreciated
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
回答1:
Method-01:
Using switch:
HTML:
<input type="number" id="color" />
JS:
function changeColor(e){
var color;
switch(e.target.value){
case 1:
color = "red";
break;
case 2:
color = "yellow";
break;
case 3:
color = "green";
break;
default:
color = "white";
}
e.target.style.backgroundColor = color;
}
document.getElementById("color").addEventListener("input", changeColor);
Method-02:
Using if else:
HTML:
<input type="number" id="color" />
JS:
function changeColor(e){
var value = e.target.value;
var color;
if(value == 1){
color = "red";
}
else if(value == 2){
color = "yellow";
}
else if(value == 3){
color = "green";
}
else {
color = "white";
}
e.target.style.backgroundColor = color;
}
document.getElementById("color").addEventListener("input", changeColor);
回答2:
There are many ways but this is one way how you could do it:
const colors = document.querySelectorAll('.colors');
for (let color of colors) {
color.addEventListener('keyup', () => {
if (this.event.target.value == 1) {
this.event.target.style.backgroundColor = 'red';
}
else if (this.event.target.value == 2) {
this.event.target.style.backgroundColor = 'yellow';
}
else if (this.event.target.value == 3) {
this.event.target.style.backgroundColor = 'green';
}
else {
this.event.target.style.backgroundColor = 'inherit';
}
})
}
<input type="text" class="colors">
<input type="text" class="colors">
<input type="text" class="colors">