应使用 <input type="search"> 而非 type="text",因其原生支持搜索键盘、自动清空并触发 search 事件、保存历史记录、语义化识别为搜索框;需配 name 和 method="get" 才构成可用搜索入口。

直接用 <input type="search"> 就行,别手写样式或 JS 模拟——浏览器原生支持、语义正确、自带清空按钮和历史记录,还兼容屏幕阅读器。
为什么不用 <input type="text"> 代替?
虽然能显示,但会丢掉三个关键能力:
• type="search" 在 Safari/iOS 上自动触发搜索键盘(带“搜索”回车键)
• 点击右侧 × 图标时,input 值清空并触发 input 和 search 事件(type="text" 不触发 search)
• 浏览器可自动保存搜索关键词,下次输入时下拉提示(需配合 name 属性)
• 屏幕阅读器会把 type="search" 识别为“搜索框”,而 type="text" 只是“文本框”
怎么加搜索图标和清空按钮?
不需要额外写 JS 或 CSS 控制显隐:
• 清空按钮(×)是 type="search" 的默认行为,只要不设 appearance: none 或覆盖 ::-webkit-search-cancel-button 就一直存在
• 搜索图标建议用 <label> 包裹 + aria-hidden="true",例如:
<label for="q"><span aria-hidden="true">?</span></label><input type="search" id="q" name="q">
• 别用背景图或伪元素硬塞图标——会影响高对比度模式和缩放体验
提交搜索时要注意什么?
多数人直接套用 <form>,但容易踩两个坑:
• 忘记加 method="get":导致搜索词无法出现在 URL 中,用户刷新/分享链接就丢失上下文
• 把 <input type="search"> 放在 <form> 外:回车不提交,必须点按钮
• 正确写法:
<form action="/search" method="get"><input type="search" name="q" required><button type="submit">搜索</button></form>
•
name="q" 是关键:它让提交后 URL 变成 /search?q=xxx,后端和前端都靠这个取值
立即学习“前端免费学习笔记(深入)”;
最常被忽略的是 name 属性和 method="get" 的组合——没它们,搜索框就只是个好看的输入框,不是真正可用的搜索入口。


















