有没有一种快速的方法来创建一个输入文本元素,在右边有一个图标,以清除输入元素本身(如谷歌搜索框)?

我环顾四周,但我只发现如何把一个图标作为输入元素的背景。有jQuery插件或其他什么?

我想在输入文本元素内的图标,类似于:

--------------------------------------------------
|                                               X|
--------------------------------------------------

当前回答

你可以使用一个带有图像样式的重置按钮…

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>

在这里查看它的实际操作:http://jsbin.com/uloli3/63

其他回答

下面是一个jQuery插件(最后还有一个演示)。

http://jsfiddle.net/e4qhW/3/

我这样做主要是为了说明一个例子(也是一个个人挑战)。虽然点赞很受欢迎,但其他答案都很准时,值得他们应有的认可。

然而,在我看来,这是过度设计的膨胀(除非它成为UI库的一部分)。

我的建议是,如果你不介意仅限于html 5兼容的浏览器,只需使用:

<input type="search" />

JS小提琴演示

不可否认,在Chromium (Ubuntu 11.04)中,这确实要求在明文图像/功能出现之前在输入元素中有文本。

参考:

深入HTML 5:一种疯狂的形式。 输入类型=搜索-搜索字段(新)HTML5。

由于没有一个解决方案能够真正满足我们的需求,我们想出了一个简单的jQuery插件,叫做jQuery- clearsearch -

使用它就像:

<input class="clearable" type="text" placeholder="search">

<script type="text/javascript">
    $('.clearable').clearSearch();
</script>

​ 例如:http://jsfiddle.net/wldaunfr/FERw3/

你可以使用一个带有图像样式的重置按钮…

<form action="" method="get">
   <input type="text" name="search" required="required" placeholder="type here" />
   <input type="reset" value="" alt="clear" />
</form>

<style>
   input[type="text"]
   {
      height: 38px;
      font-size: 15pt;
   }

   input[type="text"]:invalid + input[type="reset"]{
     display: none;
   } 

   input[type="reset"]
   {
      background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
      background-position: center center;
      background-repeat: no-repeat;
      height: 38px;
      width: 38px;
      border: none;
      background-color: transparent;
      cursor: pointer;
      position: relative;
      top: -9px;
      left: -44px;
   }
</style>

在这里查看它的实际操作:http://jsbin.com/uloli3/63

不需要包含CSS或图像文件。不需要包含整个沉重的jQuery UI库。我写了一个轻量级的jQuery插件,为你做的魔法。你所需要的只是jQuery和插件。=)

jQuery InputSearch演示。