我正在尝试创建一个搜索栏,允许用户在需要时清除其文本。问题是在第一次按键后出现清除按钮。如果输入字段中没有文本,则反过来会明显发生。
HTML
<input type="text">
<span>x</span>
CSS
span {cursor: pointer;}
的jQuery
$('span').hide();
//Clears the Input Box
$('span').mousedown(function() {
$(this).siblings('input[type="text"]').val('');
});
//Shows/Hides the Clear Button
$('input[type="text"]').on('focus', function() {
if ($(this).val().length > 0) {
$('span').show();
} else {
$('span').hide();
}
}).blur(function() {
$('a').hide();
});
答案 0 :(得分:4)
使用oninput检测用户何时与文本框进行交互
$('input').on('focus input', function () {
$('span').toggle(this.value.length>0);
}).blur(function () {
$('span').hide();
});
其他选项是对支持它的浏览器使用type =“search”。有些人已经添加了按钮并处理了这个。
答案 1 :(得分:1)
$('input[type="text"]').keyup(function(){
if(($(this).val().length) > 0) {
$("#clearfix").show();
}else {
$("#clearfix").hide();
}
});
只要在文本框中输入或删除任何文本,keyup就会运行。这允许您检查输入文本的长度以查看是否输入了任何文本。
更新:
jQuery('input').bind('input propertychange', function() {
if(($(this).val().length) > 0) {
$('span').show();
}else {
$('span').hide();
}
});
更新版本将在文本框中的任何更改时运行。当您使用键盘输入文本时,它将在您粘贴文本时运行。
如果您只想在文本框中包含TEXT时查找它,那么这对您有用。