How do I add a “search” button in a text input field?

前端 未结 7 1368
梦毁少年i
梦毁少年i 2020-11-27 18:49

How do I create a similar “search” element to the one in this site?

\"enter

If

相关标签:
7条回答
  • 2020-11-27 19:31

    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

    0 讨论(0)
  • 2020-11-27 19:32

    I'd like to plug a new jQuery plugin I wrote because I feel it answers to the OP's request. It's called jQuery.iconfield: https://github.com/yotamofek/jquery.iconfield.

    It lets you easily add an icon to the left side of your text field. For using the icon as a button, you can easily bind to the 'iconfield.click' event, which is triggered when the user clicks the icon. It also takes care of changing the cursor when the mouse is hovering over the icon.

    For instance:

    $('#search-field').iconfield( {
        'image-url':   'imgs/search.png', // url of icon
        'icon-cursor': 'pointer'          // cursor to show when hovering over icon
    } );
    $('#search-field').on( 'iconfield.click', function( ) {
        $('#search-form').submit()
    }
    

    I would love to get some feedback on my work.

    0 讨论(0)
  • 2020-11-27 19:33

    To help with user feedback why not add the pointer icon to your mouse when you're hovering over the magnifying glass? Just att this to your CSS:

    .search:hover { cursor:pointer; }

    0 讨论(0)
  • 2020-11-27 19:38

    If you view the page in Google Chrome, right-click on the search button and select “Inspect element”, you’ll be able to see the CSS used to achieve this effect.

    If you’re not familiar with CSS, I thoroughly recommend ‘CSS: The Definitive Guide’.

    0 讨论(0)
  • 2020-11-27 19:38

    A site like Iconspedia has a number of free icons that are similar.

    Wherever you get the icon be careful to ensure that you have the rights to use it in your application. Many graphics are protected and some have restrictive licenses.

    0 讨论(0)
  • 2020-11-27 19:43

    If you use a background image on the field then there's no way to bind to it to get the click action. So the solution is to have a separate search field and image, so you can bind click event in jQuery to the image. Fiddle here:

    http://jsfiddle.net/Lzm1k4r8/23/

    You can adjust left: position to be left or right side of the search box.

    0 讨论(0)
提交回复
热议问题