将a添加
type="search"到您的输入中
该支持相当不错,但在IE <10中不起作用
<input type="search">
旧浏览器的可清除输入
如果您需要IE9支持,请采取以下解决方法
使用标准
<input type="text">和一些HTML元素:
$(".clearable").each(function() { var $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{ 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 { display: none;}<span > <input type="text" name="" value="" placeholder=""> <i >×</i></span><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
仅使用(没有其他元素)
设置一个·并使用它的背景图片:
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{ background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center; border: 1px solid #999; padding: 3px 18px 3px 4px; border-radius: 3px; transition: background 0.4s;}.clearable.x { background-position: right 5px center; } .clearable.onX{ cursor: pointer; } .clearable::-ms-clear {display: none; width:0; height:0;} <input type="text" name="" value="" placeholder="" /><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
技巧是为设置一些右填充(我使用18px),input然后将背景图像向右推,以至看不见(我使用right -10px center)。
18px的填充将防止文本隐藏在图标下方(可见时)。
jQ将添加显示清除图标的类x(如果input有值)。
现在我们需要的是用jQ作为类的输入目标,x并检测mousemove鼠标是否在18px“ x”区域内;如果在内部,则添加class onX。
单击onX类将删除所有类,重置输入值并隐藏图标。
base64字符串:
data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=



