JavaScript实例

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索..">
<ul id="myUL">
    <li><a href="#">Google</a></li>
    <li><a href="#">Runoob</a></li>
    <li><a href="#">Taobao</a></li>
    <li><a href="#">Wiki</a></li>
    <li><a href="#">Facebook</a></li>
    <li><a href="#">Zhihu</a></li>
    <li><a href="#">Weibo</a></li>
</ul>
<style>
    #myInput {
      background-image: url('https://statiwww.jyshare.com/images/mix/searchicon.png'); /* 添加搜索按钮 */
      background-position: 10px 12px; /* 定位搜索按钮 */
      background-repeat: no-repeat; /* 图片不重复 */
      width: 100%; /* 全屏幕显示 */
      font-size: 16px; /* 字体大小 */
      padding: 12px 20px 12px 40px; /* 设置内边距 */
      border: 1px solid #ddd; /* 添加灰色边框 */
      margin-bottom: 12px; /* 添加顶部的外边距 */
    }
     
    #myUL {
      /* 移除默认的列表样式 */
      list-style-type: none;
      padding: 0;
      margin: 0;
    }
     
    #myUL li a {
      border: 1px solid #ddd; /* 链接添加边框 */
      margin-top: -1px; /* 防止边框重复 */
      background-color: #f6f6f6; /* 设置灰色背景 */
      padding: 12px; /* 添加内边距 */
      text-decoration: none; /* 移除默认的下划线 */
      font-size: 18px; /* 设置字体大小 */
      color: black; /* 设置文本为黑色 */
      display: block; /* 以块形式填充到列表 */
    }
     
    #myUL li a:hover:not(.header) {
      background-color: #eee; /* 为所有链接添加悬停效果,标题除外 */
    }
</style>
<script>
    function myFunction() {
      // 声明变量
      var input, filter, ul, li, a, i, txtValue;
      input = document.getElementById('myInput');
      filter = input.value.toUpperCase();
      ul = document.getElementById("myUL");
      li = ul.getElementsByTagName('li');
     
      // 循环遍历所有列表项,并隐藏那些与搜索查询不匹配的项
      for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        txtValue = a.textContent || a.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          li[i].style.display = "";
        } else {
          li[i].style.display = "none";
        }
      }
    }
</script>