首页 > 解决方案 > 在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 个字母或清空边框底部仍为绿色。

标签: javascripthtmlcss

解决方案


尝试这个。

我只是将事件更改onkeypressonkeyup. 两者的不同之处在于,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()">


推荐阅读