2012-12-24 102 views
13
<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> 

在上面的代码中,我想添加一个搜索图标用于与按钮产生的每个新的输入(ID =添加;在此未示出为简单起见)。这将是一个典型的输入:添加搜索图标,输入框

<label> 
<input type="text" class="search" name="word" autofocus="autofocus" /> 
<span class="search-icon"> 
    <span class="glass"></span> 
    <span class="handle"></span> 
</span> 
</label> 

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

感谢

回答

25

下面是我使用的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> 

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

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

<input type="search" results> 

与搜索图标。输入类型搜索使其成为一个搜索框,用“x”按钮清除,添加“结果”也显示搜索框。当然,你也可以添加一个CSS和JavaScript的x按钮到常规搜索框中。注意输入类型搜索允许非常少的样式也很重要。演示在Safari在Mac上:

Demo

告诉我,如果这可以帮助你,并确保标记为答案。 :)

+0

AMAZING解释,毫无疑问它会工作,但是,你知道,如果我可以,比方说,让搜索框透明,或更改的颜色搜索图标? – j1nma

+0

好吧,我提供的代码在搜索框中搜索到搜索图标,因此使搜索框变为透明图标。当然,您可以使用相对定位,这样可以使搜索图标和搜索框独立。你可以编辑搜索图标来改变颜色(这不能在CSS中完成),或者修改照片编辑程序的不透明度,或者从头开始改变颜色,但我有点像我的搜索图标。 :)这里是相对定位的例子:http://jsfiddle.net/525h6/。您也可以通过追踪来完成此操作,但这将会很有帮助 – 2012-12-24 16:56:51

+0

关于我的答案中的代码“outline:0”,我当时毫无头绪,我认为您最好阅读http://outlinenone.com/。 – 2012-12-28 02:06:48

4

使用background-image把图像到跨度中,例如,然后给它一个相对位置,将其移动到左侧,使其重叠的搜索框右端,例如:

#g-search-button { 
    display: inline-block; 
    width: 16px; 
    height: 16px; 
    position: relative; 
    left: -22px; 
    top: 3px; 

    background-color: black; /* Replace with your own image */ 
} 

Working example on JSBin

注:这不是我的答案,我发现它here

3

有上kirupa.com这里一步步:http://www.kirupa.com/html5/creating_an_awesome_search_box.htm

随着你在这里CSS的相关位:

input[type=text] { 
    width: 260px; 
    padding: 5px; 
    padding-right: 40px; 
    outline: none; 
    border: 2px solid #999999; 
    border-radius: 5px; 
    background-color: #FBFBFB; 
    font-family: Cambria, Cochin, Georgia, serif; 
    font-size: 16px; 
    background-position: 270px -10px; 
    background-image: url('http://www.kirupa.com/images/search.png'); 
    background-repeat: no-repeat; 
}