javascript - 在javascript中输入小于最小长度时如何引起注意
问题描述
当值的长度小于3个字母时,我试图使输入的底部边框为红色,如果超过3个则为绿色
function pclck1() {
"use strict";
var x = document.getElementById("fname").value;
if (x.length >= 2) {
document.getElementById("fname").style.borderBottomColor = "#0d0";
} else {
document.getElementById("fname").style.borderBottomColor = "#f00";
}
}
<input id="fname" type="text" placeholder="Type Here!" onkeypress="pclck1()">
它在打字时工作,但在使用退格键并删除字母后,直到值的长度变为 2 或 1 个字母或清空边框底部仍为绿色。
解决方案
尝试这个。
我只是将事件更改onkeypress
为onkeyup
. 两者的不同之处在于,onkeypress
当您按下一个键时就会起作用。但是onkeyup
当我们按下后释放一个键时它会起作用
function pclck1() {
"use strict";
var x = document.getElementById("fname").value;
if (x.length >= 3) {
document.getElementById("fname").style.borderBottomColor = "#0d0";
} else {
document.getElementById("fname").style.borderBottomColor = "#f00";
}
}
<input id="fname" type="text" placeholder="Type Here!" onkeyup="pclck1()">
推荐阅读
- amazon-web-services - 在 AWS 上尝试 Dask
- php - 如果在 Woocommerce 中应用了任何优惠券代码,请删除一些支付网关
- selenium-webdriver - 如果条件为真,则获取 webelements 列表
- protractor - 在量角器中上传外部文件
- android - 带有firebase后端的android studio中的Instamojo PG
- java - “spring.data.web.pageable.one-indexed-parameters=true”不起作用
- jquery - 图片点击库上的简单jquery
- sql-server - 在 SSMS 中,我如何使用 DATEADD 函数来获取 '2018-09-01 00:00:00.000' 和 '2018-09-01 023:59:00.000' 之间的所有值
- php - 用于博客数据的php mysql查询增加/加载Web服务器上的内存
- google-cloud-platform - 如何指定哪些网站 url 可以使用您的 Google API 编号