JavaScript--模拟百度搜索下拉li

上效果:

 

 

主要思路:

函数indexOf() 、join()、innerHTML的使用,还有 用完的数组要清空

 1 <!DOCTYPE html>
 2 <html>
 3 <head lang="en">
 4     <meta charset="UTF-8">
 5     <title></title>
 6     <style>
 7         * {
 8             margin: 0;
 9             padding: 0;
10         }
11         body {
12             font-size: 20px;
13         }
14         .box {
15             width: 600px;
16             height: 40px;
17             margin: 200px auto;
18             position: relative;
19         }
20         #txt {
21             width: 488px;
22             height: 38px;
23             border: 1px solid #3385ff;
24             font-size: 20px;
25             float: left;
26             outline: none;
27             padding-left: 10px;
28         }
29         #search {
30             width: 100px;
31             height: 40px;
32             float: left;
33             border:0 none;
34             background-color: #3385ff;
35             color:#fff;
36             cursor: pointer;
37         }
38         #keywords {
39             position: absolute;
40             top: 40px;
41             left: 0;
42             background-color: rgb(12, 255, 24);
43             list-style: none;
44             width: 500px;;
45         }
46         li {
47             line-height: 24px;
48         }
49     </style>
50 </head>
51 <body>
52 <div class="box">
53     <div class="baidu">
54         <input type="text" id="txt"/>
55         <input type="button" value="百度一下" id="search"/>
56     </div>
57     <ul id="keywords"></ul>
58 </div>
59 <script>
60 
61     // 这里是模拟我们的数据库
62     var keywords = ["冬天吃什么","冬天的离别","冬天有多冷","林丹林丹","林丹夺冠","123","123456","JavaScript","Java","黄鳝","黄鳝煮汤","黄鳝煮粥","咸鱼","咸鱼茄子煲","咸鱼翻身","十九大","十八大","十全十美"];
63     var txt = document.getElementById('txt');
64     var search = document.getElementById('search');
65     var ul = document.getElementById('keywords');
66 
67     txt.onkeyup = function () {
68         // 取出目前输入的关键字
69         var txtValue = txt.value.trim();
70 
71         //存储与当前关键字相关的字符串信息的数组
72         var aimArr = [];
73         for(var i = 0 ; i < keywords.length ; i++ ) {
74             // keywords数组中的字符串是否含义该关键字,含有的话存储进aimArr
75             if(keywords[i].indexOf(txtValue) != -1) { // 没有返回-1
76                 aimArr.push(keywords[i]);
77             }
78         }
79         // 如果输入为空
80         if (txtValue.length == 0 ) {
81             aimArr = [];
82         }
83 
84         // 把aimArr设置进ul中js动态添加的li里面
85         // 创建li
86         var lis = []; // 新创建的li存储在lis数组里面
87         for(var i = 0 ; i < aimArr.length ; i++ ) {
88             lis.push("<li>"+aimArr[i]+"</li>");
89         }
90         // 把lis数组转为字符串,添加进ul中
91         ul.innerHTML = lis.join("");
92 
93     }
94 
95 
96 
97 </script>
98 </body>
99 </html>

 

posted @ 2017-10-19 21:06  QinXiao.Shou  阅读(229)  评论(0编辑  收藏  举报