在html5页面开发中,给搜索框添加清除历史按钮是提升用户交互体验的常见需求,用户点击该按钮可以快速清空输入框内容,也可以同步清除对应的搜索历史记录,不需要手动逐字删除输入内容。

基础结构搭建
首先我们需要搭建搜索框和清除按钮的基础html结构,搜索框使用input元素,类型为search,清除按钮可以自定义样式,默认处于隐藏状态,只有当输入框有内容时才显示。
<div class="search-wrapper"> <input type="search" id="searchInput" placeholder="请输入搜索内容"> <button type="button" id="clearBtn" class="clear-btn">×</button> </div>
基础样式设置
接下来给搜索区域和清除按钮添加基础样式,让清除按钮定位在搜索框的右侧,默认隐藏,只有输入框有内容时才显示。
.search-wrapper {
position: relative;
width: 300px;
margin: 20px;
}
#searchInput {
width: 100%;
height: 36px;
padding-right: 30px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
outline: none;
}
#searchInput:focus {
border-color: #409eff;
}
.clear-btn {
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
width: 20px;
height: 20px;
border: none;
background: #ccc;
color: #fff;
border-radius: 50%;
cursor: pointer;
display: none;
font-size: 12px;
line-height: 20px;
text-align: center;
}
.clear-btn:hover {
background: #999;
}
清除按钮显示隐藏逻辑
我们需要监听input元素的输入事件,当输入框的值不为空时显示清除按钮,为空时隐藏清除按钮。
// 获取元素
const searchInput = document.getElementById('searchInput');
const clearBtn = document.getElementById('clearBtn');
// 监听输入事件
searchInput.addEventListener('input', function() {
if (this.value.length > 0) {
clearBtn.style.display = 'block';
} else {
clearBtn.style.display = 'none';
}
});
清除按钮事件绑定
给清除按钮绑定点击事件,点击时清空输入框内容,同时隐藏清除按钮,如果需要清除搜索历史,还可以同步处理本地存储的历史记录。
// 清除按钮点击事件
clearBtn.addEventListener('click', function() {
// 清空输入框内容
searchInput.value = '';
// 隐藏清除按钮
this.style.display = 'none';
// 让输入框失去焦点,可选
searchInput.blur();
// 如果需要清除本地存储的搜索历史,可以执行以下逻辑
// localStorage.removeItem('searchHistory');
});
清除历史记录的实现
如果搜索历史是存储在localStorage中的,我们可以在点击清除按钮时同步清除对应的历史数据,以下是完整的处理逻辑示例。
// 假设搜索历史存储格式为JSON字符串数组
// 保存搜索历史的示例方法
function saveSearchHistory(keyword) {
let history = localStorage.getItem('searchHistory');
history = history ? JSON.parse(history) : [];
// 去重处理
if (!history.includes(keyword)) {
history.unshift(keyword);
// 最多保存10条历史
if (history.length > 10) {
history = history.slice(0, 10);
}
localStorage.setItem('searchHistory', JSON.stringify(history));
}
}
// 清除按钮点击时同步清除历史
clearBtn.addEventListener('click', function() {
searchInput.value = '';
this.style.display = 'none';
// 清除本地存储的搜索历史
localStorage.removeItem('searchHistory');
console.log('搜索历史已清除');
});
注意事项
- 清除按钮的样式可以根据项目设计需求调整,比如使用图标代替默认的×符号
- 如果输入框的内容是通过其他方式赋值的,比如js直接设置
value属性,需要手动触发显示隐藏逻辑 - 清除历史记录的逻辑需要和项目存储历史的方式匹配,比如如果是存储在后端接口,需要调用对应的删除接口
- 输入框类型为
search时,部分浏览器自带默认的清除按钮,可通过css隐藏默认按钮:input[type="search"]::-webkit-search-cancel-button { display: none; }