我认为:placeholder-shown
选择器非常酷。 当存在占位符时,它允许您选择<input placeholder="...">
( <input placeholder="...">
)。 意思是,输入还没有任何值。 您可能会认为input[value]
可以做到这一点,或帮助匹配实际值,但是不能。
这使得:placeholder-shown
为我们拥有的少数CSS属性之一,可以对用户启动的状态作出反应,这些状态包括:hover
-and-friends, :checked
( checkbox hack !)和也很棒的:focus-within
。
我们可以使用它的一种方法是检查用户是否在搜索字段中输入了任何文本 。 如果是,则以视觉方式显示搜索按钮(对于辅助技术,请不要将其隐藏)。 如果否,则将其隐藏。 这只是一个有趣的小“节省空间”技术,与浮动标签不同,这并不可怕。
因此,也许我们从语义搜索形式开始:
<form action="#" method="GET" class="search-form">
<!-- Placeholders aren't labels! So let's have a real label -->
<label for="search" class="screen-reader-text">Search</label>
<input id="search" type="search" class="search-input" placeholder="Enter search terms...">
<button class="search-button">Search</button>
</form>
我们将使用那些特殊的仅用于屏幕阅读器的类之一在视觉上隐藏搜索标签,因为它将始终以视觉方式隐藏。 但是,我们将按钮隐藏在窗体外,并隐藏了溢出,以隐藏该按钮。
.search-form {
/* we'll re-use this number, so DRYing up */
--searchButtonWidth: 75px;
overflow: hidden;
position: relative;
}
.search-input {
/* take full width of form */
width: 100%;
}
.search-button {
position: absolute;
/* push outside the form, hiding it */
left: 100%;
width: var(--searchButtonWidth);
}
然后,诀窍是当占位符消失(用户输入了一个值)时将搜索按钮拉回:
/* ... */
.search-input:not(:placeholder-shown) ~ .search-button {
/* pull back the negative value of the width */
transform: translateX(calc(-1 * var(--searchButtonWidth)));
}
.search-button {
position: absolute;
left: 100%;
width: var(--searchButtonWidth);
/* animate it */
transition: 0.2s;
}
最终像这样:
我在利亚姆·约翰斯顿(Liam Johnston)的钢笔中看到了这个想法。 不错的主意,利亚姆!
我知道完全使用placeholder
属性是有问题的 ,因此您的工作量可能会有所不同。 我承认,直接在CSS中对其状态处理方面以及如何使用它(例如臭名昭著的复选框hack)最感兴趣。
支持很好。 当Edge牢固地带有铬时,它就是其中之一。
该浏览器支持数据来自Caniuse ,其更多信息。 数字表示浏览器支持该版本及更高版本的功能。
桌面
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
47 | 51 | 11* | 79 | 9 |
手机/平板电脑
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
81 | 68 | 81 | 9.0-9.2 |
翻译自: https://css-tricks.com/show-search-button-when-search-field-is-non-empty/