6

在 Google 上搜索时,自动填充结果会显示在下方,就像许多其他网站一样。

但除此之外,对于出现在输入框中的最可能的搜索查询,还有一个褪色的文本自动完成功能,而不会改变光标的位置。请参阅随附的屏幕截图。我检查了控制台,但那里没有任何用处。

在此处输入图像描述

这样的效果是如何实现的?

4

2 回答 2

4

谷歌通过设置一个单独input元素的值来做到这一点,该元素直接堆叠在“活动”元素的后面。如果查看源代码,您可以看到在同一个地方有许多元素:

<div id="gs_lc0" style="position: relative;">
    <input id="gbqfq" class="gbqfif" name="q" type="text" autocomplete="off" value="" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; background-image: url(data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D); background-color: transparent; position: absolute; z-index: 6; left: 0px; outline: none; background-position: initial initial; background-repeat: initial initial;" dir="ltr" spellcheck="false">
    <div class="gbqfif" style="background-color: transparent; color: transparent; padding: 0px; position: absolute; z-index: 2; white-space: pre; visibility: hidden; background-position: initial initial; background-repeat: initial initial;" id="gs_sc0"></div>
    <input class="gbqfif" disabled="" autocomplete="off" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; -webkit-text-fill-color: silver; color: silver; left: 0px;" id="gs_taif0" dir="ltr">
    <input class="gbqfif" disabled="" autocomplete="off" style="border: none; padding: 0px; margin: 0px; height: auto; width: 100%; position: absolute; z-index: 1; background-color: transparent; -webkit-text-fill-color: silver; color: silver; left: 0px; visibility: hidden;" id="gs_htif0" dir="ltr">
</div>

第二个<input>似乎正在处理灰色的建议文本。

于 2012-11-25T11:49:30.433 回答
1

这是通过两个输入和 CSS 属性完成的position: absolute。一个输入为黑色,包含当前用户输入,第二个输入为灰色,位于第一个输入的下方。

其 CSS 可能如下所示:

input.user-input {
    position: absolute;
    background: transparent;
    color: #000;
    z-index: 2
}
input.suggest-input {
    position: absolute;
    color: #ccc;
    z-index: 1
}
于 2012-11-25T11:50:34.837 回答