邮箱填写功能

209 阅读1分钟

邮件地址输入框提醒功能

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
        <style>
            li:hover {
                background: #ccc;
                cursor: pointer;
            }
    
            body {
                height: 800px;
            }
        </style>
    </head>
    
    <body id="body">
        <div class="wrapper">
            <input id="email-input" type="text">
            <ul id="email-sug-wrapper" class="email-sug"></ul>
        </div>
    </body>
    <script>
        var postfixList = ['163.com', 'gmail.com', '126.com', 'qq.com', '263.net'];
        var str = '';
        $('#email-input').bind('input propertychange', function () {  //监听数据变化
            var term = $("#email-input").val();
            $('#email-sug-wrapper').css("display", "block");
            if (term) {
                term = getCaption(term)
                for (i = 0; i < postfixList.length; i++) {
                    str += "<li>" + term + "@" + postfixList[i] + "</li>"
                }
                $('#email-sug-wrapper').html(str);
                str = ''
            } else {
                $('#email-sug-wrapper').css("display", "none");
            }
        })
        $('#email-input').focus(function () {  //输入框获取焦点的事件处理
            $('#email-sug-wrapper').css("display", "block");
            var term = $("#email-input").val();
    
            if (term) {
                term = getCaption(term)
                console.log(term);
                for (i = 0; i < postfixList.length; i++) {
                    str += "<li>" + term + "@" + postfixList[i] + "</li>"
                }
                $('#email-sug-wrapper').html(str);
                str = ''
            }
        })
    
        // 截取字符串
    
        function getCaption(obj) {
            var index = obj.lastIndexOf("\@");
            // 截取@之前的字符串
            if (index > 0) {
                obj = obj.substring(0, index);
            }
            return obj;
        }
        window.onload = function () {
            document.getElementById("body").addEventListener("click", function (e) {  //事件委托监听
                console.log(e.target.nodeName)
                if (e.target.nodeName == "LI") {
    
                    var t = e.target.innerHTML;
                    $('#email-input').val(t);
                    $('#email-sug-wrapper').css("display", "none");
                }
                if (e.target.nodeName == 'BODY') {
                    $('#email-sug-wrapper').css("display", "none");
                }
            });
        }
    
    </script>
    
    </html>