javascript - 仅当输入第二个错误字符时,文本输入的边框才会改变颜色 - Javascript
问题描述
我正在构建一个小费计算器,如果输入“非数字”,我希望文本输入变为红色,如果输入数字则变为绿色。
与号码配合良好。一旦我输入一个数字,边框就会变成绿色,但是如果我输入一个字母,第一个字母就会变成绿色,然后只有当第二个字母被输入时它才会变成红色。
如果页面刚刚加载并且之前输入了值,则会发生这种情况。
我尝试使用onkeyup
and更改触发器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>
解决方案
您需要使用该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">
推荐阅读
- javascript - 当所有孩子都被绝对定位时如何弯曲(或类似的影响)
- sql - 选择上一个 x 季度日期
- pandas - pandas read_csv dtype 定义:int,int64,'Int64'
- javascript - How to get the summation of iterated FormArray
- php - shell_exec 没有在 websever 中运行
- image - Flutter Image.Network 和 CachedNetworkImage 不显示?
- vue.js - 是否可以在 Vue 的选择表单中使用 v-model 更改两个值?
- python - 如何在 Python 的窗口中(例如在数字手表上)显示和更新文本?
- http - Blazor webassembly:检测用户来自哪个站点
- python - 当您将 2 个变量分配给一个函数时会发生什么?