You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

用户聚焦搜索input输入框时如何实现关联内容文本推荐

搜索框聚焦展示关联推荐功能实现方案

核心逻辑是监听输入框的focus事件,触发后渲染预设或动态拉取的推荐内容列表,同时配套点击填充、失焦隐藏等交互。

1. 调整HTML结构

在原有输入框基础上增加父容器和推荐列表承载节点:

<div class="search-container">
  <input type="text" placeholder="Search..." id="searchInput">
  <ul class="suggestion-list" id="suggestionList"></ul>
</div>

2. 编写基础样式

实现推荐列表的定位、默认隐藏、交互态样式:

.search-container {
  position: relative;
  width: 320px;
}
#searchInput {
  width: 100%;
  padding: 8px 12px;
  box-sizing: border-box;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.suggestion-list {
  position: absolute;
  top: calc(100% + 2px);
  left: 0;
  right: 0;
  margin: 0;
  padding: 0;
  list-style: none;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
  display: none;
  z-index: 1000;
}
.suggestion-list li {
  padding: 8px 12px;
  cursor: pointer;
}
.suggestion-list li:hover {
  background-color: #f5f5f5;
}
/* 父容器处于聚焦状态且列表有内容时显示 */
.search-container:focus-within .suggestion-list.show {
  display: block;
}

3. 编写交互逻辑

// 预设关联推荐词,可根据当前页面属性动态配置,也可替换为接口请求获取
const relatedSuggestions = ['最佳手机', '2021年最佳笔记本', '千元平板推荐', '降噪耳机测评']
const searchInput = document.getElementById('searchInput')
const suggestionList = document.getElementById('suggestionList')

// 渲染推荐列表
function renderList(list) {
  suggestionList.innerHTML = ''
  if (!list.length) {
    suggestionList.classList.remove('show')
    return
  }
  list.forEach(item => {
    const li = document.createElement('li')
    li.innerText = item
    // 点击推荐词自动填充到输入框
    li.addEventListener('click', () => {
      searchInput.value = item
      // 如需点击后直接触发搜索,可在此处补充对应逻辑
    })
    suggestionList.appendChild(li)
  })
  suggestionList.classList.add('show')
}

// 监听输入框聚焦事件,触发推荐展示
searchInput.addEventListener('focus', () => {
  renderList(relatedSuggestions)
})

// 可选:输入内容时实时过滤推荐列表
searchInput.addEventListener('input', () => {
  const keyword = searchInput.value.trim()
  const filtered = relatedSuggestions.filter(item => item.includes(keyword))
  renderList(filtered)
})

// 点击页面其他区域隐藏推荐列表
document.addEventListener('click', (e) => {
  if (!e.target.closest('.search-container')) {
    suggestionList.classList.remove('show')
  }
})

如果需要推荐内容根据页面动态变化,只需在focus事件触发时调用后端接口,拉取当前页面对应的推荐词列表后再渲染即可。

内容的提问来源于stack exchange,提问作者mahdi8405

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:18:05