如何使用 JavaScript 在密码可见性之间切换?


若要通过 JavaScript 在密码可见性之间切换,代码如下所示 −

示例

 实时演示

<!DOCTYPE html>
<html>
<head>
<h1>Password visibility example</h1>
Password:
<input type="password" value="abcd@1234" id="inputPass" /><br /><br />
<input class="check" type="checkbox" />Show Password
<h2>Click on the above checkbox to see your password as text</h2>
<script>
   document.querySelector(".check").addEventListener("click", showPass);
   function showPass() {
      var inputPassEle = document.getElementById("inputPass");
      if (inputPassEle.type === "password") {
         inputPassEle.type = "text";
      } else {
         inputPassEle.type = "password";
      }
   }
</script>
</body>
</html>

输出

上述代码会产生以下输出 −

选中显示密码复选框时 −

更新于: 06-May-2020

156 次浏览

开启您的 事业

完成课程以获得认证

开始
广告
© . All rights reserved.