答案:通过HTML结构、CSS样式和JavaScript交互实现搜索框输入提示效果。.search-container设置相对定位,.search-input定义输入框样式,.suggestions使用绝对定位浮于上方,圆角边框阴影提升视觉效果,JS监听输入动态过滤数据并展示匹配项,点击或键盘操作可选中,提升可用性。
制作一个美观实用的搜索框输入提示(Autocomplete Suggestions)效果,可以通过 HTML + CSS 实现基础样式,再配合 JavaScript 动态控制显示内容。以下是一个简洁、可复用的 CSS 样式方案。
使用一个容器包裹输入框和提示列表:
为输入框和提示列表设置样式,确保提示层浮在上方、有圆角、阴影和悬停效果:
.search-container {
position: relative;
width: 300px;
}
.search-input {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 6px;
outline: none;
}
.suggestions {
position: absolute;
top: 100%;
left: 0;
right: 0;
margin: 0;
padding: 0;
list-style: none;
background: #fff;
border: 1px solid #ddd;
border-top: none;
border-radius: 0 0 6px 6px;
max-height: 200px;
overflow-y: auto;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
z-index: 1000;
display: none; / 默认隐藏 /
}
.suggestions.show {
display: block; / 显示时激活 /
}
.suggestions li {
padding: 10px;
cursor: pointer;
transition: background-color 0.2s;
}
.suggestions li:hover,
.suggestions li.selected {
background-color: #f0f0f0;
}
虽然重点是 CSS,但简单 JS 可让提示出现更自然:
const input = document.querySelector('.search-input');
const suggestions = document.querySelector('.suggestions');
// 模拟数据
const data = ['苹果', '香蕉', '橙子', '葡萄', '草莓'];
input.addEventListener('input', function() {
const value = this.value.trim().toLowerCase();
suggestions.innerHTML = '';
if (value) {
const filtered = data.filter(item => item.toLowerCase().includes(value));
filtered.forEach(item => {
const li = document.createElement('li');
li.textContent = item;
suggestions.appendChild(li);
});
suggestions.classList.add('show');
} else {
suggestions.classList.remove('show');
}
});
// 点击选项填充输入框
suggestions.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
input.value = e.target.textContent;
suggestions.classList.remove('show');
}
});
提升用户体验的小细节:
基本上就这些。CSS 负责视觉呈现,JS 控制逻辑,结构清晰且易于扩展。