写一个密码默认星号,但可以查看密码的输入框

15 min read

可以使用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类型。