如何使用 JavaScript 切換密碼可見性?
本文中,我們將把密碼隱藏為 ****。可以透過使用按鈕切換其可見性來顯示密碼。我們將建立 JavaScript 函式,以便在單擊切換按鈕時顯示隱藏的密碼。
方法
單擊切換按鈕後,將呈現 display password JavaScript 函式。
這將會更改應用於將顯示密碼的 HTML 輸入標記上的 CSS 屬性。
我們可以再次切換以再次隱藏密碼。
示例
在以下示例中,我們使用 checkboxcheckbox 切換密碼的可見性。單擊 checkbox 按鈕後將顯示密碼,否則將隱藏密碼。
# index.html
<!DOCTYPE html> <html> <head> <title> Toggle Password Visibility </title> </head> <body> <h2 style="color:green"> Welcome To Tutorials Point </h2> <div class="container"> <h3 class="mt-5 mb-5 text-center">Toggle password visibility</h3> <div class="form-group"> <label for="ipnPassword">Password</label> <div class="input-group mb-3"> <input type="password" class="form-control" id="ipnPassword"/> <div class="input-group-append"> <input type="checkbox" class="btn btn-outline-secondary" type="button" id="btnPassword">Show Password </button> </div> </div> </div> </div> </body> <script> // step 1 const ipnElement = document.querySelector('#ipnPassword') const btnElement = document.querySelector('#btnPassword') // step 2 btnElement.addEventListener('click', function() { // step 3 const currentType = ipnElement.getAttribute('type') // step 4 ipnElement.setAttribute('type',currentType === 'password' ? 'text' : 'password') }) </script> </html>
輸出
廣告