首页 > 编程技术 > js

javascript实现输入框内容提示及隐藏功能

发布时间:2021-9-30 00:02

有时输入框较小,希望输入内容后,出现一个有放大输入内容的提示框

实现思路

注意这里是键盘松开事件,不要用键盘按下事件:keydown或keypress,按下时还没有将打的字录入,键盘松开时,才会录入打的字

代码示例:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>模拟京东快递单号查询</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        input {
            outline-style: none;
        }
        
        .search {
            position: relative;
            width: 220px;
            margin: 100px auto;
        }
        
        .info {
            display: none;
            position: absolute;
            top: -40px;
            left: 0;
            width: 170px;
            padding: 5px 0;
            font-size: 18px;
            line-height: 20px;
            border: 1px solid rgba(0, 0, 0, .2);
            box-shadow: 0px 2px 4px rgba(0, 0, 0, .2);
        }
        
        .info::before {
            content: '';
            width: 0;
            height: 0;
            position: absolute;
            top: 28px;
            left: 18px;
            border: 8px solid #000;
            border-color: #fff transparent transparent;
            border-style: solid dashed dashed;
        }
    </style>
</head>

<body>
    <div class="search">
        <div class="info">(*´▽`)ノノ</div>
        <input type="text" class="express" placeholder="请输入要查询的快递单号">
        <input type="button" value="查询">
    </div>
    <script>
        var expressNo = document.querySelector('.express');
        var info = document.querySelector('.info');


        expressNo.addEventListener('keyup', function() {
            console.log(expressNo.value);
            console.log(info.innerHTML);
            if (this.value == '') {
                info.style.display = 'none';
            } else {
                info.style.display = 'block';
                info.innerHTML = this.value;
            }
        });


        // 失去焦点,隐藏盒子
        expressNo.addEventListener('blur', function() {
            info.style.display = 'none';
        })

        //获得焦点事件,显示盒子
        expressNo.addEventListener('focus', function() {
            if (this.value !== '') {
                info.style.display = 'block';
            }
        })
    </script>
</body>

</html>

页面效果:

快递单号查询.gif

到此这篇关于javascript实现输入框内容提示及隐藏功能的文章就介绍到这了,更多相关js输入框内容提示及隐藏内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

标签:[!--infotagslink--]

您可能感兴趣的文章: