当前位置:首页 > JavaScript

js实现搜索框

2026-02-03 03:29:18JavaScript

实现基础搜索框功能

创建一个基础的HTML搜索框结构,包含输入框和搜索按钮:

<input type="text" id="searchInput" placeholder="输入搜索内容">
<button id="searchButton">搜索</button>
<div id="searchResults"></div>

添加基本的事件监听和搜索逻辑:

document.getElementById('searchButton').addEventListener('click', function() {
  const searchTerm = document.getElementById('searchInput').value.trim();
  if (searchTerm) {
    performSearch(searchTerm);
  }
});

function performSearch(term) {
  // 模拟搜索数据
  const data = ['苹果', '香蕉', '橙子', '葡萄', '西瓜'];
  const results = data.filter(item => item.includes(term));

  displayResults(results);
}

function displayResults(results) {
  const resultsContainer = document.getElementById('searchResults');
  resultsContainer.innerHTML = '';

  if (results.length === 0) {
    resultsContainer.innerHTML = '<p>没有找到匹配的结果</p>';
    return;
  }

  const ul = document.createElement('ul');
  results.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item;
    ul.appendChild(li);
  });

  resultsContainer.appendChild(ul);
}

添加实时搜索功能

实现输入时实时触发搜索的功能:

document.getElementById('searchInput').addEventListener('input', function(e) {
  const searchTerm = e.target.value.trim();
  if (searchTerm.length >= 2) { // 至少输入2个字符才触发搜索
    performSearch(searchTerm);
  }
});

添加防抖优化

防止频繁触发搜索请求:

let debounceTimer;

document.getElementById('searchInput').addEventListener('input', function(e) {
  clearTimeout(debounceTimer);
  const searchTerm = e.target.value.trim();

  debounceTimer = setTimeout(() => {
    if (searchTerm.length >= 2) {
      performSearch(searchTerm);
    }
  }, 300); // 300毫秒延迟
});

实现搜索历史功能

添加搜索历史记录功能:

let searchHistory = [];

function addToHistory(term) {
  if (!searchHistory.includes(term)) {
    searchHistory.unshift(term);
    if (searchHistory.length > 5) {
      searchHistory.pop();
    }
    renderHistory();
  }
}

function renderHistory() {
  const historyContainer = document.getElementById('searchHistory');
  if (!historyContainer) return;

  historyContainer.innerHTML = '';
  const ul = document.createElement('ul');

  searchHistory.forEach(item => {
    const li = document.createElement('li');
    li.textContent = item;
    li.addEventListener('click', () => {
      document.getElementById('searchInput').value = item;
      performSearch(item);
    });
    ul.appendChild(li);
  });

  historyContainer.appendChild(ul);
}

添加样式美化

为搜索框添加基本CSS样式:

#searchInput {
  padding: 8px 12px;
  width: 300px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

#searchButton {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#searchResults {
  margin-top: 20px;
}

#searchHistory {
  margin-top: 10px;
  color: #666;
}

完整示例代码

整合所有功能的完整实现:

<!DOCTYPE html>
<html>
<head>
  <style>
    #searchInput {
      padding: 8px 12px;
      width: 300px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
    #searchButton {
      padding: 8px 16px;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    #searchResults {
      margin-top: 20px;
    }
    #searchHistory {
      margin-top: 10px;
      color: #666;
    }
  </style>
</head>
<body>
  <input type="text" id="searchInput" placeholder="输入搜索内容">
  <button id="searchButton">搜索</button>
  <div id="searchHistory"></div>
  <div id="searchResults"></div>

  <script>
    let searchHistory = [];
    let debounceTimer;

    document.getElementById('searchButton').addEventListener('click', function() {
      const searchTerm = document.getElementById('searchInput').value.trim();
      if (searchTerm) {
        performSearch(searchTerm);
        addToHistory(searchTerm);
      }
    });

    document.getElementById('searchInput').addEventListener('input', function(e) {
      clearTimeout(debounceTimer);
      const searchTerm = e.target.value.trim();

      debounceTimer = setTimeout(() => {
        if (searchTerm.length >= 2) {
          performSearch(searchTerm);
        }
      }, 300);
    });

    function performSearch(term) {
      const data = ['苹果', '香蕉', '橙子', '葡萄', '西瓜'];
      const results = data.filter(item => item.includes(term));
      displayResults(results);
    }

    function displayResults(results) {
      const resultsContainer = document.getElementById('searchResults');
      resultsContainer.innerHTML = '';

      if (results.length === 0) {
        resultsContainer.innerHTML = '<p>没有找到匹配的结果</p>';
        return;
      }

      const ul = document.createElement('ul');
      results.forEach(item => {
        const li = document.createElement('li');
        li.textContent = item;
        ul.appendChild(li);
      });

      resultsContainer.appendChild(ul);
    }

    function addToHistory(term) {
      if (!searchHistory.includes(term)) {
        searchHistory.unshift(term);
        if (searchHistory.length > 5) {
          searchHistory.pop();
        }
        renderHistory();
      }
    }

    function renderHistory() {
      const historyContainer = document.getElementById('searchHistory');
      if (!historyContainer) return;

      historyContainer.innerHTML = '';
      const ul = document.createElement('ul');

      searchHistory.forEach(item => {
        const li = document.createElement('li');
        li.textContent = item;
        li.addEventListener('click', () => {
          document.getElementById('searchInput').value = item;
          performSearch(item);
        });
        ul.appendChild(li);
      });

      historyContainer.appendChild(ul);
    }
  </script>
</body>
</html>

js实现搜索框

标签: js
分享给朋友:

相关文章

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 使用JavaScript实现拖拽功能需要监听鼠标事件,包括mousedown、mousemove和mouseup。以下是实现的基本逻辑: const draggableElem…

js实现拖拽

js实现拖拽

实现拖拽的基本步骤 通过监听鼠标事件(mousedown、mousemove、mouseup)实现拖拽功能。以下是核心代码逻辑: const draggableElement = document.…

js 实现继承

js 实现继承

原型链继承 通过让子类的原型对象指向父类的实例来实现继承。子类实例可以访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Par…

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…