CSS 和 JS 实现搜索历史(仿淘宝APP)

185 阅读1分钟

以下是一个简单的示例,演示如何使用 HTML、CSS 和 JavaScript 来实现一个搜索历史功能,类似于淘宝APP。

HTML 结构

<div class="search-container">
  <input type="text" id="searchInput" placeholder="搜索" />
  <button id="searchBtn">搜索</button>
</div>
<div class="history-container">
  <h3>搜索历史</h3>
  <ul id="historyList">
    <!-- 动态添加搜索历史 -->
  </ul>
  <button id="clearHistory">清除历史</button>
</div>

CSS 样式

.search-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

#searchInput {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

#searchBtn {
  padding: 10px 20px;
  margin-left: 10px;
}

.history-container {
  border-top: 1px solid #ccc;
  padding-top: 10px;
}

#historyList {
  list-style: none;
  padding: 0;
  margin: 0;
}

#historyList li {
  padding: 8px;
  border-bottom: 1px solid #ccc;
}

#clearHistory {
  display: block;
  margin-top: 10px;
}

JavaScript 代码

我们将使用 localStorage 来存储搜索历史。

document.addEventListener("DOMContentLoaded", function () {
  const searchInput = document.getElementById("searchInput");
  const searchBtn = document.getElementById("searchBtn");
  const historyList = document.getElementById("historyList");
  const clearHistory = document.getElementById("clearHistory");

  // 加载历史记录
  loadHistory();

  // 搜索按钮点击事件
  searchBtn.addEventListener("click", function () {
    const query = searchInput.value.trim();
    if (query) {
      saveHistory(query);
      loadHistory();
      searchInput.value = "";
    }
  });

  // 清除历史按钮点击事件
  clearHistory.addEventListener("click", function () {
    localStorage.removeItem("searchHistory");
    loadHistory();
  });

  // 保存搜索历史到 localStorage
  function saveHistory(query) {
    let history = localStorage.getItem("searchHistory");
    history = history ? JSON.parse(history) : [];
    if (!history.includes(query)) {
      history.unshift(query);
    }
    localStorage.setItem("searchHistory", JSON.stringify(history));
  }

  // 从 localStorage 加载搜索历史
  function loadHistory() {
    let history = localStorage.getItem("searchHistory");
    history = history ? JSON.parse(history) : [];
    historyList.innerHTML = "";
    history.forEach((item) => {
      const li = document.createElement("li");
      li.textContent = item;
      historyList.appendChild(li);
    });
  }
});

这个示例包括一个搜索输入框和一个搜索按钮。当用户点击搜索按钮后,输入的文本会被保存到搜索历史中(使用 localStorage)。下方有一个搜索历史列表,列出所有之前搜索过的词,以及一个“清除历史”按钮来删除所有的搜索历史。

你可以根据需要进一步定制这个示例。