adding search icon to input box

2019-03-15 06:46发布

问题:

<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>

Within the code above, i want to add a search icon for every new input generated with a button (id=add ; not shown here for simplicity). This would be a typical input:

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

With CSS i could position the search icons in a fixed way.

Thanks

回答1:

Here's the CSS code that I'd use:

<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>

Note: I added a lot of extra codes to make the search box look better, the necessary code to make the search box apear is padding-left, background-image:url, background-repeat and background-position. Replace "http://i47.tinypic.com/r02vbq.png" with whatever search icon you want.

It's also important to know that now in HTML5, most browsers render

<input type="search" results>

with a search icon. The input type search makes it a search box, with a "x" button to clear, and adding "results" also displays a search box. Of course you could also add an x button with CSS and JavaScript to a regular search box. It's also important to note that input type search allows very little styling. Demo on Safari on a Mac:

Tell me if this helps you, and make sure to mark as the answer. :)



回答2:

Put the image into the span, for example using background-image, then give it a relative position and move it to the left so it overlaps the right end of the search box, for example:

#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

Note: This is not my answer, i've found it here



回答3:

There's a step by step on kirupa.com here: http://www.kirupa.com/html5/creating_an_awesome_search_box.htm

With relevant bit of CSS for you here:

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;
}