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

我环顾四周,但我只发现如何把一个图标作为输入元素的背景。有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>

其他回答

jQuery Mobile现在内置了:

<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">

Jquery移动API TextInput文档

我已经使用jQuery和bootstrap编写了一个简单的组件。 试试吧:https://github.com/mahpour/bootstrap-input-clear-button

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

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

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

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

如果你想让它像谷歌一样,那么你应该知道“X”实际上并不在<input>中——它们是彼此相邻的,外部容器样式看起来像文本框。

HTML:

<form>
    <span class="x-input">
        <input type="text" class="x-input-text" />
        <input type="reset" />
    </span>
</form>

CSS:

.x-input {
    border: 1px solid #ccc;
}

.x-input input.x-input-text {
    border: 0;
    outline: 0;
}

例如:http://jsfiddle.net/VTvNX/

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

使用它就像:

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

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

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