首页 > 解决方案 > 仅当输入第二个错误字符时,文本输入的边框才会改变颜色 - Javascript

问题描述

我正在构建一个小费计算器,如果输入“非数字”,我希望文本输入变为红色,如果输入数字则变为绿色。

与号码配合良好。一旦我输入一个数字,边框就会变成绿色,但是如果我输入一个字母,第一个字母就会变成绿色,然后只有当第二个字母被输入时它才会变成红色。

如果页面刚刚加载并且之前输入了值,则会发生这种情况。

我尝试使用onkeyupand更改触发器onkeydown,但没有奏效,而且我很确定这无论如何都不是解决方案。

片段

function checking() {
  let hey = document.querySelector('.checkInput')
  let hello = document.querySelector('.howMuch')

  if(isNaN(hey.value)) {
    hey.style.border = '1px solid red'
  }
  else {
    hey.style.border = '1px solid green'
  }
}
.red {
  color: red;
}

input:focus::placeholder {
  color: transparent;
}

input {
  outline: none;
}
<div class="container">
    <label for="checkInput">How much is the check?</label>
    <input class="checkInput" onkeypress="checking()" id="checkInput" type="text"><br>
</div>

标签: javascript

解决方案


您需要使用该keyup事件,因为“keypress”上尚未实际插入文本:

function checking(e) {
  const input = document.querySelector('.checkInput')

  if(isNaN(input.value)) {
    input.style.border = '1px solid red'
  }
  else {
    input.style.border = '1px solid green'
  }
}
.red {
  color: red;
}

input:focus::placeholder {
  color: transparent;
}

input {
  outline: none;
}
<div class="container">
    <label for="checkInput">Input: </label>
    <input class="checkInput" onkeyup="checking()" id="checkInput" type="text"><br>
</div>

按键生命周期演示:

const inp = document.querySelector('#test');

inp.addEventListener("keyup", log);
inp.addEventListener("keypress", log);
inp.addEventListener("keydown", log);

function log(event){
  console.log(event.type, inp.value);
}
<input id="test">


推荐阅读