使用placeHolder属性在输入(type=text)中加载图标

load icon in input(type=text) using placeHolder attribute

本文关键字:text 加载 图标 type 属性 placeHolder 输入 使用      更新时间:2023-09-26

我使用了以下代码片段

<input type="text" class="inputtext" style="margin: 2px;" placeholder="Search">

我有自己的字体图标,我想通过占位符在输入中显示图标。如何使用内容在输入

中显示图标

我引用了下面的堆栈溢出链接

stackoverflow联系

但是在我的情况下我不能做到。是否有任何方法来实现这个或任何其他文档链接显示字体图标的输入?

检查这个演示jsFiddle

HTML

<input type="text" class="inputtext" placeholder="Search">
CSS

input { 
    font-family: 'FontAwesome';
    background-image: url(http://www.levenmetwater.nl/static/global/images/icon-search.png);
    background-position: 10px center;
    background-repeat: no-repeat;
    text-indent: 30px;
}
input:focus {
    background-position: -20px center;
    text-indent: 0;
}

没有input:focus

演示jsFiddle

假设您正在谈论添加字形图标而不是背景图像到您的输入,您将需要使用:before:after伪元素来注入和定位一个,但是请注意这些不可用于input元素,因此您需要将input包装在例如span中,然后应用样式来添加占位符图标。在下面的示例中,我只是在右侧添加了一个小放大镜,不过您可以根据需要进行编辑。

Demo Fiddle(右侧图标)

HTML

<span class='search'><input type="text" class="inputtext" style="margin: 2px;" placeholder="Search" /></span>
CSS

.search{
    display:inline-block;  
    position:relative;
}
.search:after{
    display:inline-block;
    position:absolute;
    right:5px;
    top:5px;
    color:grey;
    font-family:fontAwesome;
    content:''f002';
}

Demo Fiddle(左侧图标)

如果你想让图标出现在输入的左边,你需要一些额外的CSS技巧:

input{
    border:none;
    padding-left:20px;
}
.search {
    display:inline-block;
    position:relative;
    border:1px solid grey;
}
.search:after {
    display:inline-block;
    position:absolute;
    left:3px;
    top:3px;
    color:grey;
    font-family:fontAwesome;
    content:''f002';
}

演示小提琴(隐藏焦点上的图标)

如果你想隐藏焦点上的图标,你只需要给输入一个背景色和一个有焦点和没有焦点的z-index, :focus的z-index应该足够高,以迫使它在图标的前面显示。

CSS:

input{
    z-index:0;
    position:relative;
}
.search{
    display:inline-block;  
    position:relative;
}
.search:after{
    display:inline-block;
    position:absolute;
    right:5px;
    top:5px;
    color:grey;
    font-family:fontAwesome;
    content:''f002';
}
input:focus{
    z-index:99;
}