可以使用HTML的input
元素,并设置其type
属性为password
,同时在该输入框上添加一个按钮,点击该按钮时可以切换密码是否可见。
下面是一个示例代码:
<input type="password" id="password-input"> <button id="toggle-visibility-button">Show Password</button> <script> const passwordInput = document.getElementById("password-input"); const toggleVisibilityButton = document.getElementById("toggle-visibility-button"); toggleVisibilityButton.addEventListener("click", () => { if (passwordInput.type === "password") { passwordInput.type = "text"; toggleVisibilityButton.textContent = "Hide Password"; } else { passwordInput.type = "password"; toggleVisibilityButton.textContent = "Show Password"; } }); </script>
在上面的示例中,当用户单击toggle-visibility-button
按钮时,脚本将检查password-input
输入框的类型属性,并相应地切换其类型。如果密码输入框是password
类型,则将其类型更改为text
类型(以便可以查看密码)。否则,将其类型更改为原始的password
类型。