互联创盟网
创盟源码

实现记住账号密码功能html5代码

发布日期: 2023-01-27  人气指数: -

1.为表单添加两个多选控件:

<div class="remember" style="text-align: center;margin: 10px auto;">
    <input type="checkbox" id="rem_username">记住账号
    <input type="checkbox" id="rem_password">记住密码
</div>

c7c5789848214db89a213e630915d5ea.png

2.编写js,监听用户名、密码输入框id:

<script type="text/javascript">
    var u_name = document.querySelector('#username');
    var u_pass = document.querySelector('#password');
    var rem_username = document.querySelector('#rem_username');
    var rem_password = document.querySelector('#rem_password');
    if (localStorage.getItem('u_name')) {
        u_name.value = (localStorage.getItem('u_name'))
        rem_username.checked = true;
    }
    if (localStorage.getItem('u_pass')) {
        u_pass.value = (localStorage.getItem('u_pass'))
        rem_password.checked = true;
    }
    rem_username.addEventListener('change',function () {
        if (this.checked) {
            localStorage.setItem('u_name', u_name.value);
        } else {
            localStorage.removeItem('u_name');
        }
    })
    rem_password.addEventListener('change',function () {
        if (this.checked) {
            localStorage.setItem('u_pass', u_name.value);
        } else {
            localStorage.removeItem('u_pass');
        }
    })
</script>

  document.querySelector用户获取单个元素,addEventListener去监听多选框是否发生改变,判断是否进行填充用户名、密码。