css - 输入中带有图标的自定义占位符

标签 css

我正在尝试为我的“搜索”输入创建一个自定义占位符。它应该看起来像一个搜索图标(为此使用 Bootstrap glyphicon glyphicon-search 类),然后是单词“Search”,在输入元素内,就像一个占位符一样,并且居中。

我正在尝试将包含这些元素的 div 定位到输入中的元素,但我无法正确定位。

这是 jsfiddle 中的代码.

HTML:

<div class="search-wrapper">
    <form class="post_search" id="post_search" action="/posts/explore" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓">
        <input autocomplete="off" class="search-input" type="search" name="q[caption_or_user_user_name_cont]" id="q_caption_or_user_user_name_cont">
        <div class="placeholder">
            <div>
                <span class="glyphicon glyphicon-search"></span>
                <span>Search</span>
            </div>
        </div>
    </form>
</div>

CSS:

.search-wrapper {
  max-width: 340px;
  margin: 0 auto;
  text-align: center;
  margin-top: 20px;
  display: inline;
}

.search-wrapper .search-input {
  border: 1px solid #ddd;
  border-radius: 15px;
  background-color: #eee;
  width: 220px;
  height: 31px;
  padding: 10px 15px;
  transition: 0.25s all;
}

.search-wrapper .search-input:focus {
  outline: 0 none;
  background-color: #fff;
  transition: 0.25s all;
}

.search-wrapper .placeholder {
  display: inline;
  position: relative;
  top: 30%;
  width: 40px;
  margin: 0 auto;
  text-align: center;
  font-size: 10px;
}

然后当专注于输入时,占位符应该消失了,我想这对一些 js 来说应该不难。

但是回到问题,我做错了什么?如何按预期显示占位符?

最佳答案

为什么不极大地简化这个?您已经在 HTML 中内置了 placeholder!您可以执行以下操作:

input[type="search"]::-webkit-input-placeholder:before {
  content: "\e003  ";
  font-family: 'Glyphicons Halflings';
}

input[type="search"]:-moz-placeholder:before {
  content: "\e003  ";
  font-family: 'Glyphicons Halflings';

input[type="search"]::-moz-placeholder:before {
  content: "\e003  ";
  font-family: 'Glyphicons Halflings';
}

input[type="search"]:-ms-input-placeholder:before {  
  content: "\e003  ";
  font-family: 'Glyphicons Halflings';
}
<input type='search' placeholder='search here' />

现在不用担心,这里没有显示图标,因为我没有包含 font-awesome(或者 Glyphicons Halflings 字体由),但这使得创建一个漂亮的占位符变得非常简单。它甚至像一个一样工作!它还大大减少了您的代码,尽管浏览器支持有点不那么出色(这实际上取决于您想要返回多远)。

Font Awesome 使用 unicode 字形和包含所有这些图标的字体,因此只要您使用正确的字体并将正确的字符复制到您的 content 属性中,它就可以工作。

已在 Safari 和 Chrome 中测试

关于css - 输入中带有图标的自定义占位符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968354/

相关文章:

css - 如何在元素不错位的情况下调整菜单的边距和填充

html - 为什么按钮不在同一层?

html - Fontawesome 将关闭的文件夹更改为打开的文件夹

html - -Windows Phone 中的 webkit-tap-highlight-color?

HTML 模板不工作

javascript - playgroundinc.com中的导航效果是如何实现的

javascript - <link rel ="stylesheet"...> 和 &lt;script ...> 标签的顺序是否重要?

html - 为禁用 JavaScript 的浏览器显示脚本的最佳实践

css - 位置 : sticky not working in firefox

html - 将 Logo 和链接放在标题中的同一行