清除输入框内的图标

226
有没有一种快速的方法来创建一个带有清除输入框自身的图标(类似于 Google 搜索框)的输入文本元素?我找了一下,但我只找到了如何将图标作为输入元素的背景。是否有 jQuery 插件或其他东西? 我想要将图标放在输入文本元素内部,像这样:
--------------------------------------------------
|                                               X|
--------------------------------------------------

3
一个jQuery插件,用于将图片定位在输入框上方?我是否漏掉了什么或者怎么了?! - Christian
1
@Christian Sciberras,从我选择的答案可以看出,它可以是一个jQuery插件... - Giovanni Di Milia
1
你可以使用jQuery插件来显示普通的警告框。但这并不意味着你真的必须这样做,在大多数情况下,这是过度设计和膨胀的。顺便说一下,你选择的不是一个jQuery插件,而是JavaScript、HTML和CSS的混合体。插件应该是一个包含相关细节的单个文件/脚本,具有jQuery签名。 - Christian
1
@Christian Sciberras:我可以区分jQuery插件和JavaScript和CSS的混合使用。我的意思是,如果你想做一些好看的东西,你不能只在输入框上放一个图片。 - Giovanni Di Milia
寻找此问题解决方案的人也需要以下信息:如何检测“搜索”HTML5输入框的清除? - brasofilo
一个插件不需要是单个文件,它确实可以是HTML、CSS和jQuery的混合物,所以很高兴看到你@GiovanniDiMilia坚持自己的立场! - luke_mclachlan
18个回答

436

向你的输入框添加 type="search" 属性。
该支持相当不错,但在 IE<10 中无法工作

<input type="search">


老旧的浏览器

如果您需要支持 IE9,这里有一些解决方法。

使用标准的 <input type="text"> 和一些 HTML 元素:

/**
 * Clearable text inputs
 */
$(".clearable").each(function() {
  
  const $inp = $(this).find("input:text"),
      $cle = $(this).find(".clearable__clear");

  $inp.on("input", function(){
    $cle.toggle(!!this.value);
  });
  
  $cle.on("touchstart click", function(e) {
    e.preventDefault();
    $inp.val("").trigger("input");
  });
  
});
/* Clearable text inputs */
.clearable{
  position: relative;
  display: inline-block;
}
.clearable input[type=text]{
  padding-right: 24px;
  width: 100%;
  box-sizing: border-box;
}
.clearable__clear{
  display: none;
  position: absolute;
  right:0; top:0;
  padding: 0 8px;
  font-style: normal;
  font-size: 1.2em;
  user-select: none;
  cursor: pointer;
}
.clearable input::-ms-clear {  /* Remove IE default X */
  display: none;
}
<span class="clearable">
  <input type="text" name="" value="" placeholder="">
  <i class="clearable__clear">&times;</i>
</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

仅使用<input class="clearable" type="text">(无其他元素)

在输入框内部放置清除图标

设置class="clearable",并调整其背景图片:

/**
 * Clearable text inputs
 */
function tog(v){return v ? "addClass" : "removeClass";} 
$(document).on("input", ".clearable", function(){
    $(this)[tog(this.value)]("x");
}).on("mousemove", ".x", function( e ){
    $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]("onX");
}).on("touchstart click", ".onX", function( ev ){
    ev.preventDefault();
    $(this).removeClass("x onX").val("").change();
});

// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
/*
    Clearable text inputs
*/
.clearable{
  background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
  border: 1px solid #999;
  padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
  border-radius: 3px;
  transition: background 0.4s;
}
.clearable.x  { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
<input class="clearable" type="text" name="" value="" placeholder="" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

用一些正确的内边距(我使用了18px)来设置 input ,并将背景图片向右推,超出视线范围(我使用了 right -10px center )。那个18px 的内边距将防止文本隐藏在图标下面(同时可见)。jQuery 将添加类 "x" (如果 input 具有值),显示清除图标。现在我们需要使用 jQ 定位具有类 x 的输入,并检测 mousemove 是否在那个18像素的 "x" 区域内;如果在,添加类 onX 。单击 onX 类会删除所有类,重置输入值并隐藏该图标。

7x7px gif: Clear icon 7x7

Base64 字符串:

data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=

5
我借鉴了这段代码中的一些思路,制作了一个标签云生成器(通过纯CSS标签和顶踩按钮)。我希望它在你的浏览器中能够正常显示。请访问http://jsfiddle.net/7PnKS/查看。 - mrBorna
1
哇,真是个好的解决方案。这正是我在寻找的。谢谢你。但是,我该如何将“x”图像更改为使用Bootstrap 3 glyphicon?因为glyphicon是字体,所以当缩小时它显示得更好。 - user1995781
1
不错,但背景图像可能会与其他CSS冲突。下面wldaunfr的答案提到了一个很棒的jQuery插件:http://plugins.jquery.com/clearsearch/ - Nick Westgate
1
最新版本的Firefox和Chrome对我很有效,但是我不得不将.on('touchstart click', '.onX', ...更改为.on('touchstart click', '.onX, .x', ...才能在iOS上正常工作。 - kritzikratzi
1
我对第一种选择的问题是:OP没有指定这是一个搜索框,只是要求它像Google搜索框一样有一个清除按钮。作为良好的语义Web开发人员,如果不是搜索框,我们不应该将其标记为搜索框。这会误导搜索引擎、屏幕阅读器和其他读取标记而不是呈现UI的任何东西认为它是一个搜索框。 - sfarbota
显示剩余39条评论

63

13
帮助其他开发者:如果你使用 Bootstrap CSS 平台,请在 bootstrap.css 文件中的 input[type="search"] 选择器中删除样式 "-webkit-appearance: textfield;"。同时保留其他样式,如 -webkit-box-sizing、-moz-box-sizing 和 box-sizing。 - Riccardo Bassilichi
1
有没有办法改变X的颜色? - Howard
2
@RiccardoBassilichi,有没有一种方法可以扩展我的CSS文件,以便我不必编辑原始的bootstrap.css文件,仍然可以使其正常工作? - supersan
我认为不行!但是我不是CSS巫师! :-( - Riccardo Bassilichi
6
很遗憾,Firefox 不支持这一功能,可以查看链接了解详情:https://developer.mozilla.org/en-US/docs/Web/CSS/::-webkit-search-cancel-button - Guillaume Husta
显示剩余2条评论

33

根据MDN的说法, <input type="search" /> 目前在所有现代浏览器中都得到支持:

input type=search

<input type="search" value="Clear this." />


然而,如果您想要在各种浏览器上实现一致的不同行为,这里有一些轻量级的替代方案,只需要使用JavaScript:

选项1 - 总是显示“x”:(示例在此)

Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
<p>Always display the 'x':</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>

选项2 - 仅在鼠标悬停在字段上时显示'x': (示例在此处)


意思是,当鼠标悬停在该字段上时,会出现一个“x”符号,点击该符号将删除该字段。

Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
  display: block;
}
.clearable-input > [data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
<p>Only display the 'x' when hovering over the field:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>

选项 3 - 仅在 input 元素有值时显示 'x':(示例在此处)

Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
  var input = el.querySelector('input');

  conditionallyHideClearIcon();
  input.addEventListener('input', conditionallyHideClearIcon);
  el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
    input.value = '';
    conditionallyHideClearIcon();
  });

  function conditionallyHideClearIcon(e) {
    var target = (e && e.target) || input;
    target.nextElementSibling.style.display = target.value ? 'block' : 'none';
  }
});
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
<p>Only display the 'x' if the `input` element has a value:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>


30

你可以使用一个用图像样式化的重置按钮...

<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


11
这会重置整个表单,而不仅仅是一个字段。 - konung
当输入为空时如何隐藏重置图像?KOGI,您能给一个实时示例吗? - Harry

26

1
太好了!提供一些关于浏览器支持的信息会很有帮助。 - Ian Newson
1
今天在我的电脑上,Firefox 27.0.1 版本出现了故障。 - Nick Westgate
4
文本没有被重新定位以为“x”按钮腾出空间,你无法看到按钮后面的文本。 - CrimsonChris
1
这仍然清除整个表单,而不仅仅是一个字段。 - Erik Veland

9

由于现有的解决方案都无法满足我们的需求,所以我们开发了一个简单的 jQuery 插件叫做 jQuery-ClearSearch -

使用它非常简单:

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

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

​ Example: http://jsfiddle.net/wldaunfr/FERw3/


在Firefox 45中工作 - Jeff Davis
2
似乎在最新的Google Chrome(v.70 ~ Nov 2018)中无法正常工作。 - Ben Clarke

5
如果你希望像谷歌一样,那么你应该知道 "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/

4

在设计模式下将文本框类型更改为“搜索”

<input type="search">

1
在Firefox中无法工作(已使用v115.0进行测试)。 - Simpler

3

编辑:我找到了这个链接,希望能有所帮助。 http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html

您提到希望它位于输入文本的右侧。因此,最好的方法是在输入框旁边创建一个图像。如果您想在框内放置内容,可以使用背景图像,但您可能无法编写清除框的脚本。

因此,插入一张图片并编写JavaScript代码以清除文字框。


我是指输入框右侧,但在输入框内部,就像谷歌所做的那样。 - Giovanni Di Milia
使用类似按钮的背景图像,并使用以下代码 <input type="text" name="Search" value="Search..." onclick="this.value='';"> - Jaspero
这不是我想要做的:我想要一个图标,只有在点击时才清除输入... - Giovanni Di Milia

3

使用简单的绝对定位 - 这并不难。

jQuery:

$('span').click(function(){
  $('input', $(this).parent()).val('');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>

原生JS:

var spans = document.getElementsByTagName("span");
function clickListener(e) {
  e.target.parentElement.getElementsByTagName("input")[0].value = "";
}
for (let i = 0; i < spans.length; i++) {
  spans[i].addEventListener("click", clickListener);
}
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
  <input>
  <span style="position:absolute;right:10px">x</span>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接