如今与<input type="search"> element https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search,这很简单:
<input type="search" placeholder="Search..."/>
支持的浏览器 https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button#browser_compatibility默认情况下,将自动在字段中呈现一个可用的清除按钮。
清除按钮是::-webkit-search-cancel-buttonCSS伪元素 https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button由基于 Webkit/Blink 的浏览器自动插入(尽管从技术上讲它仍然是一个非标准功能)。
如果您使用 Bootstrap,则必须添加 CSS 覆盖以强制显示伪元素:
input[type=search]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
正式地,-webkit-search-cancel-button伪元素 https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button是非标准的,不应被依赖为跨浏览器的内置 HTML 功能。
值得注意的是,从版本 110 开始,Firefox 默认情况下不会呈现清除按钮,但他们计划最终启用它:https://bugzilla.mozilla.org/show_bug.cgi?id=1654288 https://bugzilla.mozilla.org/show_bug.cgi?id=1654288。您可以查看最新的浏览器兼容性信息on MDN https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button#browser_compatibility or CanIUse.com https://caniuse.com/mdn-css_selectors_-webkit-search-cancel-button.
最可靠、面向未来的跨浏览器方法是使用表单具有明确的<input type="reset"/> element https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/reset附近允许使用按钮清除搜索表单。这也使得添加辅助功能提示和直接使用 CSS 设置透明按钮样式变得更加容易。
<form action="/search">
<input type="search" placeholder="Search..."/>
<input type="reset" value="X" alt="Clear the search form">
<input type="submit" value="Search">
</form>
Extras:Safari/WebKit浏览器还可以提供额外功能 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search#non-standard_attributes使用时type="search"
, like results=5
, enterkeyhint="..."
, and autosave="..."
,但它们也会覆盖您的许多样式(例如高度、边框)。为了防止这些覆盖,同时仍然保留 X 按钮等功能,您可以将其添加到 css 中:
input[type=search] {
-webkit-appearance: none;
}
See the MDN 文档 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search, CanIUse.com https://caniuse.com/mdn-css_selectors_-webkit-search-cancel-button, or CSS-Tricks.com https://css-tricks.com/webkit-html5-search-inputs/有关所提供功能的更完整和最新的信息<input type="search"/>
在今天的浏览器中。