亲宝软件园·资讯

展开

js实现百度淘宝搜索功能

一只前端小白 人气:0

本文实例为大家分享了js实现百度淘宝搜索功能的具体代码,供大家参考,具体内容如下

由于没有后台数据,用数组模拟一下后台返回的数据

<!DOCTYPE html>
<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>Document</title>
 <style>
  .box{
    width:214px;
    /*height: 400px;*/
    margin: 100px auto;
    position: relative;
   }
  </style>
</head>
<body>
 <div class="box">
  <input type="text" id="txt">
  <input type="button" id="btn" value="搜索">
 </div>
 <script src="common.js"></script>
 <script>
  //模拟后台的数据
  var keyWords = [
   "一马当先",
   "一箭双雕",
   "一丝不苟",
   "一心二用",
   "吃火锅",
   "吃鸡肉",
   "吃鸡腿",
   "吃鸡蛋",
   "哈1哈",
   "嘻1嘻",
   "呜1呜",
  ];
  //给文本框注册键盘松开事件
  $query("#txt").onkeyup = function () {
   var txt = $query("#txt").value;
   if ($query(".box div")) {
    $query(".box").removeChild($query(".box div"));
   }
   if (txt.length == 0) {
    if ($query(".box div")) {
     $query(".box").removeChild($query(".box div"));
    }
    return;
   }
   var newArr = [];
   for (var i = 0; i < keyWords.length; i++) {
    if (keyWords[i].indexOf(txt) !=-1) {
     newArr.push(keyWords[i]);
    }
   }
   if (newArr.length > 0) {
    var newBox = document.createElement("div");
    newBox.style.border = "1px solid red";
    newBox.style.width = "100%";
    $query(".box").appendChild(newBox);
    for (var j = 0; j < newArr.length; j++) {
     var newP = document.createElement("p");
     newP.style.width = "100%";
     newP.innerText = newArr[j];
     newP.onmouseover = function () {
      this.style.backgroundColor = "yellow";
     }
     newP.onmouseout = function () {
      this.style.backgroundColor = "";
     }
     newBox.appendChild(newP);
    }
   }
   console.log(newArr);//打印匹配的数据
  }
 </script>
</body>
</html>

最后,附上效果图,确实丑了点?

加载全部内容

相关教程
猜你喜欢
用户评论