文章目录
搜索框练习
404 Not Found
2024-11-07 15:30
累计阅读2
评论0

搜索框练习

需求

当表单得到焦点,显示下拉菜单,失去焦点隐藏下来菜单

分析

  1. 开始下拉菜单要进行隐藏
  2. 表单获得焦点 focus,则显示下拉菜单,并且文本框变色(添加类)
  3. 表单失去焦点,反向操作

代码实现

<!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>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        ul {

            list-style: none;
        }

        .mi {
            position: relative;
            width: 223px;
            margin: 100px auto;
        }

        .mi input {
            width: 223px;
            height: 48px;
            padding: 0 10px;
            font-size: 14px;
            line-height: 48px;
            border: 1px solid #e0e0e0;
            outline: none;
        }

        .mi .search {
            border: 1px solid #ff6700;
        }

        .result-list {
            display: none;
            position: absolute;
            left: 0;
            top: 48px;
            width: 223px;
            border: 1px solid #ff6700;
            border-top: 0;
            background: #fff;
        }

        .result-list a {
            display: block;
            padding: 6px 15px;
            font-size: 12px;
            color: #424242;
            text-decoration: none;
        }

        .result-list a:hover {
            background-color: #eee;
        }
    </style>

</head>

<body>
    <div class="mi">
        <input type="search" placeholder="小米笔记本">
        <ul class="result-list">
            <li><a href="#">全部商品</a></li>
            <li><a href="#">小米11</a></li>
            <li><a href="#">小米10S</a></li>
            <li><a href="#">小米笔记本</a></li>
            <li><a href="#">小米手机</a></li>
            <li><a href="#">黑鲨4</a></li>
            <li><a href="#">空调</a></li>
        </ul>
    </div>
    <script>
        const input = document.querySelector('[type=search]')
        const ul = document.querySelector('.result-list')
        // console.log(input);
        //2.监听事件
        input.addEventListener('focus', function () {
            ul.style.display = 'block'
            input.classList.add('search')
        })
        input.addEventListener('blur', function () {
            ul.style.display = 'none'
            input.classList.remove('search')
        })


    </script>
</body>

</html>
评论
404NotFound
Powered by Halo Themed by Shine
haoanlan
haoanlan
haoanlan