模拟百度搜索框实现

需求很简单,就是模拟百度搜索框的实现



<html lang="en">
<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>百度搜索框实现title>
<style type="text/css">
            * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            }
            html,
            body {
            font-size: 14px;
            font-family: "微软雅黑";
            }
            .searchBox {
            width: 300px;
            margin: 100px auto;
            }
            .searchBox input {
            display: block;
            outline: none;
            width: 100%;
            height: 30px;
            padding: 0 10px;
            border: 1px solid rebeccapurple;
            }
            ul,
            li {
            list-style: none;
            width: 100%;
            }
            ul {
            border: 1px solid #ddd;
            border-top: none;
            display: none;
            }
            li {
            padding: 0 10px;
            height: 30px;
            line-height: 30px;
            cursor: pointer;
            }
            li:hover {
            background-color: #eee;
            }
style>
head>
<body>
<div class="searchBox">
<input type="text" id="searchInput" placeholder="请输入搜索内容" autocomplete="off">
<ul id="viewContent">

ul>
div>
body>
html>
<script type="text/javascript" charset="utf-8" src="https://cdn.bootcss.com/jquery/2.1.0/jquery.min.js">script>
<script type="text/javascript" charset="utf-8">
        // https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='关键字'&cb=jQuery11020934050068638484_1563500786346&_=1563500786361
        var mySearch = (function () {
        var $searchInput = $("#searchInput"),
        $viewContent = $("#viewContent"),
        searchKey = '';
        function callBack(data) {
        var str = '';
        data = data.s;
        for (var i = 0, len = data.length; i < len; i++) {
        // 默认显示4条信息
        if (i <= 3) {
        str += "
  • " + data[i] + "
  • "
    ; } } $viewContent.html(str); $viewContent.show(); }; function bindHtml() { // getData $.ajax({ url: 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=' + searchKey, dataType: 'jsonp', jsonp: 'cb', success: callBack }) }; function init() { // 获取搜索框的关键字 $searchInput.on('focus keyup', function () { // 把空格开头和空格结尾换成空字符串 searchKey = $(this).val().replace(/(^ +| +$)/g,''); if (searchKey.length > 0) { //如果输入框有值 bindHtml(); return false; } // 输入框没有值 $viewContent.stop().slideUp(300); }).on('blur', function () { // 失去焦点搜索框收缩即可 这里的计时器是用来解决最后几个li点不到的bug setTimeout(function () { $viewContent.stop().slideUp(300); }, 100) }); // 给li绑定方法 $viewContent.on('click', "li", function (e) { $searchInput.val($(this).html()); }); }; return { init: init } })(); mySearch.init();
    script>

    你可能感兴趣的:(工作总结)