如何使用 JavaScript 找出輸入欄位中 CapsLock 是否開啟?


為了找出如何使用 JavaScript 讓輸入欄位中 CapsLock 開啟,程式碼如下 −

示例

 線上演示

<!DOCTYPE html>
<html>
<head>
<style>
   #textBox {
      display: none;
      color: red;
   }
</style>
<body>
<h1>Detecting Caps Lock Example</h1>
<input class="inputfield" value="Some textBox.." />
<h2>Press caps lock in the above input field to check warning</h2>
<h2 class="textBox">WARNING! Caps lock is ON.</h2>
<script>
   var input = document.querySelector(".inputfield");
   var textBox = document.querySelector(".textBox");
   input.addEventListener("keyup", event => {
      if (event.getModifierState("CapsLock")) {
         textBox.style.display = "block";
      } else {
         textBox.style.display = "none";
      }
   });
</script>
</body>
</html>

輸出

以上程式碼將產生以下輸出 −

在 CapsLock 開啟的情況下在輸入欄位中鍵入內容 −

更新日期: 06-May-2020

151 瀏覽量

開啟你的 職業生涯

完成此課程即可獲得認證

開始學習
廣告
© . All rights reserved.