将搜索图标添加到输入框

j1n*_*nma 14 javascript search icons input

<div id="inputs">
<input type="text" value="">
<input type="text" value="">
</div>
<input type="button" id="add" value="Add input">

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function(){
$('#add').click(function(){
 $('#inputs').append('<input type="text" value="">');
});
});
</script>
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我想为使用按钮生成的每个新输入添加搜索图标(id = add;为简单起见,此处未显示).这将是一个典型的输入:

<label>
<input type="text" class="search" name="word" autofocus="autofocus" />
<span class="search-icon">
    <span class="glass"></span>
    <span class="handle"></span>
</span>
</label>
Run Code Online (Sandbox Code Playgroud)

使用CSS,我可以以固定的方式定位搜索图标.

谢谢

小智 27

这是我使用的CSS代码:

<style>
#add{
padding:17px;padding-left:55px;width:300px;border:1px solid #f5f5f5;
font-size:13px;color:gray;
background-image:url('http://i47.tinypic.com/r02vbq.png');
background-repeat:no-repeat;
background-position:left center;outline:0;
}
</style>
Run Code Online (Sandbox Code Playgroud)

注意:我添加了许多额外的代码以使搜索框看起来更好,使搜索框apear的必要代码是padding-left,background-image:url,background-repeat和background-position.将" http://i47.tinypic.com/r02vbq.png " 替换为您想要的任何搜索图标.

同样重要的是要知道现在在HTML5中,大多数浏览器都会渲染

<input type="search" results>
Run Code Online (Sandbox Code Playgroud)

带有搜索图标.输入类型搜索使其成为搜索框,使用"x"按钮清除,添加"结果"也会显示搜索框.当然,您也可以在常规搜索框中添加带有CSS和JavaScript的x按钮.同样重要的是要注意输入类型搜索允许非常少的样式.在Mac上的Safari演示:

演示

告诉我这是否对您有所帮助,并确保将其标记为答案.:)