在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?
你似乎不能在浏览器中访问它。搜索输入是Cocoa NSSearchField的Webkit HTML包装器。取消按钮似乎包含在浏览器客户机代码中,而包装器中没有可用的外部引用。
来源:
http://weblogs.mozillazine.org/hyatt/archives/2004_07.html#005890 http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#text-state-and-search-state http://dev.w3.org/html5/markup/input.search.html#input.search
看起来你必须通过点击鼠标位置来解决这个问题,比如:
$('input[type=search]').bind('click', function(e) {
var $earch = $(this);
var offset = $earch.offset();
if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
// your code here
}
});
实际上,每当用户搜索或单击“x”时,都会触发一个“search”事件。这特别有用,因为它理解“增量”属性。
现在,话虽如此,我不确定你是否能说出点击“x”和搜索之间的区别,除非你使用“onclick”黑客。不管怎样,希望这对你有所帮助。
多托罗网络参考
根据鲍安的回答,这是有可能的。前女友。
<head>
<script type="text/javascript">
function OnSearch(input) {
if(input.value == "") {
alert("You either clicked the X or you searched for nothing.");
}
else {
alert("You searched for " + input.value);
}
}
</script>
</head>
<body>
Please specify the text you want to find and press ENTER!
<input type="search" name="search" onsearch="OnSearch(this)"/>
</body>
对我来说,点击X应该算作一个更改事件是有意义的。我已经设置了onChange事件来做我需要它做的事情。所以对我来说,修复是简单地做这一行jQuery:
$('#search').click(function(){ $(this).change(); });
发现这篇文章,我意识到它有点老了,但我想我可能有一个答案。这处理点击十字,退格和按ESC键。我相信它可以写得更好——我对javascript还是个新手。下面是我最后做的——我使用jQuery (v1.6.4):
var searchVal = ""; //create a global var to capture the value in the search box, for comparison later
$(document).ready(function() {
$("input[type=search]").keyup(function(e) {
if (e.which == 27) { // catch ESC key and clear input
$(this).val('');
}
if (($(this).val() === "" && searchVal != "") || e.which == 27) {
// do something
searchVal = "";
}
searchVal = $(this).val();
});
$("input[type=search]").click(function() {
if ($(this).val() != filterVal) {
// do something
searchVal = "";
}
});
});
将搜索事件绑定到搜索框,如下所示-
$('input[type=search]').on('search', function () {
// search logic here
// this function will be executed on click of X (clear button)
});
我想补充一个“晚”的答案,因为我今天在改变、keyup和搜索方面很挣扎,也许我最后发现的东西对其他人也有用。 基本上,我有一个搜索类型面板,我只是想对小X的压力做出正确的反应(在Chrome和Opera下,FF没有实现它),并清除内容面板作为结果。
我有这样的代码:
$(some-input).keyup(function() {
// update panel
});
$(some-input).change(function() {
// update panel
});
$(some-input).on("search", function() {
// update panel
});
(它们是分开的,因为我想检查在什么时候以及在什么情况下调用它们)。
事实证明Chrome和Firefox的反应是不同的。 特别是,Firefox将更改视为“对输入的每一次更改”,而Chrome则将其视为“当焦点丢失和内容更改时”。 因此,在Chrome上的“更新面板”函数被调用一次,在FF上的每一次击键都被调用两次(一次在keyup,一次在change)
此外,用小X清除字段(在FF下不存在)在Chrome下触发搜索事件:没有keyup,没有变化。
结论?使用input代替:
$(some-input).on("input", function() {
// update panel
}
在我测试的所有浏览器中,它都具有相同的行为,对输入内容的每一次更改都做出反应(包括使用鼠标复制粘贴、自动补全和“X”)。
搜索或onclick工作…但我发现的问题是旧的浏览器——搜索失败。很多插件(jquery ui autocomplete或fancytree filter)都有模糊和聚焦处理程序。将其添加到自动完成输入框对我来说很有效。Value == ""因为它的计算速度更快)。当你点击小“x”时,模糊然后聚焦将光标保持在方框中。
PropertyChange和input在IE 10和IE 8以及其他浏览器上都可以工作:
$("#INPUTID").on("propertychange input", function(e) {
if (this.value == "") $(this).blur().focus();
});
对于FancyTree过滤器扩展,你可以使用一个重置按钮,并强制它的点击事件如下:
var TheFancyTree = $("#FancyTreeID").fancytree("getTree");
$("input[name=FT_FilterINPUT]").on("propertychange input", function (e) {
var n,
leavesOnly = false,
match = $(this).val();
// check for the escape key or empty filter
if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === "") {
$("button#btnResetSearch").click();
return;
}
n = SiteNavTree.filterNodes(function (node) {
return MatchContainsAll(CleanDiacriticsString(node.title.toLowerCase()), match);
}, leavesOnly);
$("button#btnResetSearch").attr("disabled", false);
$("span#SiteNavMatches").text("(" + n + " matches)");
}).focus();
// handle the reset and check for empty filter field...
// set the value to trigger the change
$("button#btnResetSearch").click(function (e) {
if ($("input[name=FT_FilterINPUT]").val() != "")
$("input[name=FT_FilterINPUT]").val("");
$("span#SiteNavMatches").text("");
SiteNavTree.clearFilter();
}).attr("disabled", true);
应该能够适应这为大多数用途。
试试这个,希望能帮到你
$("input[name=search-mini]").on("search", function() {
//do something for search
});
我相信这是唯一的答案,只有当x被点击。
然而,这有点俗气,ggutenberg的答案对大多数人都适用。
$('#search-field').on('click', function(){
$('#search-field').on('search', function(){
if(!this.value){
console.log("clicked x");
// Put code you want to run on clear here
}
});
setTimeout(function() {
$('#search-field').off('search');
}, 1);
});
其中“#search-field”是输入的jQuery选择器。使用'input[type=search]'选择所有搜索输入。通过在单击字段后立即检查搜索事件(Pauan的答案)来工作。
完整的解决方案在这里
这将在单击搜索x时清除搜索。 或 当用户按回车键时,将调用搜索API。 这段代码可以通过附加的esc键up事件匹配器进一步扩展。但是这个应该能搞定。
document.getElementById("userSearch").addEventListener("search",
function(event){
if(event.type === "search"){
if(event.currentTarget.value !== ""){
hitSearchAjax(event.currentTarget.value);
}else {
clearSearchData();
}
}
});
欢呼。
点击TextField交叉按钮(X) onmousemove()被触发,我们可以使用这个事件来调用任何函数。
<input type="search" class="actInput" id="ruleContact" onkeyup="ruleAdvanceSearch()" placeholder="Search..." onmousemove="ruleAdvanceSearch()"/>
我知道这是一个老问题,但我一直在寻找类似的东西。确定点击“X”以清除搜索框的时间。这里没有一个答案对我有帮助。其中一个很接近,但也受到影响,当用户点击“enter”按钮时,它会触发与点击“X”相同的结果。
我在另一个帖子上找到了这个答案,它非常适合我,只有当用户清空搜索框时才会触发。
$("input").bind("mouseup", function(e){
var $input = $(this),
oldValue = $input.val();
if (oldValue == "") return;
// When this event is fired after clicking on the clear button
// the value is not cleared yet. We have to wait for it.
setTimeout(function(){
var newValue = $input.val();
if (newValue == ""){
// capture the clear
$input.trigger("cleared");
}
}, 1);
});
基于js的事件循环,点击clear按钮将在输入时触发搜索事件,因此下面的代码将正常工作:
input.onclick = function(e){
this._cleared = true
setTimeout(()=>{
this._cleared = false
})
}
input.onsearch = function(e){
if(this._cleared) {
console.log('clear button clicked!')
}
}
上面的代码,点击事件预约了这个。_cleared = false事件循环,但该事件将始终在onsearch事件之后运行,因此您可以稳定地检查this。_cleared状态,以确定用户是否刚刚点击X按钮,然后触发onsearch事件。
这可以在几乎所有的条件下工作,粘贴文本,具有增量属性,ENTER/ESC键按下等。
这里有一种方法。你需要添加增量属性到你的html或它不会工作。
window.onload = function() { var tf = document.getElementById('textField'); var button = document.getElementById('b'); 按钮禁用 = 真; var onKeyChange = 函数 textChange() { 按钮禁用 = (tf.value === “”) ?真 : 假; } tf.addEventListener('keyup', onKeyChange); tf.addEventListener('search', onKeyChange); } <输入 id=“文本字段” 类型=“搜索” 占位符=“搜索” 增量=“增量”> <按钮 id=“b”>去!</button>
document.querySelectorAll('input[type=search]').forEach(function (input) {
input.addEventListener('mouseup', function (e) {
if (input.value.length > 0) {
setTimeout(function () {
if (input.value.length === 0) {
//do reset action here
}
}, 5);
}
});
}
ECMASCRIPT 2016
我的解决方案是基于onclick事件,在那里我检查输入的值(确保它不是空的)在事件触发的确切时间,然后等待1毫秒,并再次检查值;如果它是空的,那么这意味着清除按钮已经被单击,而不仅仅是输入字段。
下面是一个使用Vue函数的例子:
HTML
<input
id="searchBar"
class="form-input col-span-4"
type="search"
placeholder="Search..."
@click="clearFilter($event)"
/>
JS
clearFilter: function ($event) {
if (event.target.value !== "") {
setTimeout(function () {
if (document.getElementById("searchBar").value === "")
console.log("Clear button is clicked!");
}, 1);
}
console.log("Search bar is clicked but not the clear button.");
},
2022简单,易读,简短的解决方案
哇,这么简单的问题居然有这么复杂的答案。
只需在你的搜索输入中添加一个“输入”监听器,当用户在输入中键入某些内容或单击清除图标时,它就会捕捉到。
document.getElementById('searchInput').addEventListener('input', (e) => { console.log('Input value: “${e.currentTarget.value}”'); }) <输入 id=“搜索输入” 类型=“搜索” 占位符=“搜索” />
如果你不能使用ES6+,那么下面是转换后的代码:
document.getElementById('searchInput').addEventListener('input', function(e) {
// Yay! You make it in here when a user types or clicks the clear icon
})`
最初的问题是“我能检测到点击‘x’吗?” 这可以通过在搜索事件中“牺牲”Enter来实现。
There are many events firing at different times in the lifecycle of an input box of type search: input, change, search. Some of them overlap under certain circumstances. By default, "search" fires when you press Enter and when you press the 'x'; with the incremental attribute, it also fires when you add/remove any character, with a 500ms delay to capture multiple changes and avoid overwhelming the listener. The trouble is, search generates an ambiguous event with input.value == "", because there are three ways it could have turned empty: (1) "the user pressed the 'x'", (2) "the user pressed Enter on an input with no text", or (3) "the user edited the input (Backspace, cut, etc) till the input became empty, and eventually incremental triggered the search event for the empty input".
消除歧义的最佳方法是将Enter从等式中去掉,只在按下“x”时启动搜索。您可以通过完全压制Enter键来实现这一点。我知道这听起来很傻,但是您可以通过keydown事件(在这里您也可以进行压制)、输入事件或更改事件在更好的控制情况下恢复Enter行为。搜索唯一的独特之处就是点击“x”。
如果您不使用增量,这将消除歧义。如果您使用增量,那么您可以通过输入事件实现大多数增量行为(您只需要重新实现500ms的debounning逻辑)。因此,如果您可以删除增量(或可选地用输入模拟它),这个问题可以通过使用event.preventDefault()组合搜索和keydown来回答。如果你不能放弃增量,你将继续有上面描述的一些模糊性。
下面是演示这一点的代码片段:
inpEl = document.getElementById("inp"); monitor = document.getElementById("monitor"); function print(msg) { monitor.value += msg + "\n"; } function searchEventCb(ev) { print(`You clicked the 'x'. Input value: "${ev.target.value}"`); } function keydownEventCb(ev) { if(ev.key == "Enter") { print(`Enter pressed, input value: "${ev.target.value}"`); ev.preventDefault(); } } inpEl.addEventListener("search", searchEventCb, true); inpEl.addEventListener("keydown", keydownEventCb, true); <input type="search" id="inp" placeholder="Type something"> <textarea id="monitor" rows="10" cols="50"> </textarea>
在这个简单的代码片段中,您已经将搜索变成了一个专门的事件,它只在您按下'x'时触发,并回答了最初发布的问题。你跟踪输入。值,并按下Enter键。
就我个人而言,我更喜欢在按Enter键时输入ev.target.blur()(模拟输入框失去焦点),并监视更改事件以跟踪输入。值(而不是监视输入。Value via keydown)。通过这种方式,您可以统一地跟踪输入。焦点变化的值,这可能是有用的。它适用于我,因为我只需要处理输入的事件。价值实际上已经改变了,但它可能并不适用于每个人。
下面是blur()行为的代码片段(现在即使您手动将焦点从输入框移开,也会收到消息,但请记住,只有在实际发生更改时才会看到更改消息):
inpEl = document.getElementById("inp"); monitor = document.getElementById("monitor"); function print(msg) { monitor.value += msg + "\n"; } function searchEventCb(ev) { print(`You clicked the 'x'. Input value: "${ev.target.value}"`); } function changeEventCb(ev) { print(`Change fired, input value: "${ev.target.value}"`); } function keydownEventCb(ev) { if(ev.key == "Enter") { ev.target.blur(); ev.preventDefault(); } } inpEl.addEventListener("search", searchEventCb, true); inpEl.addEventListener("change", changeEventCb, true); inpEl.addEventListener("keydown", keydownEventCb, true); <input type="search" id="inp" placeholder="Type something"> <textarea id="monitor" rows="10" cols="50"> </textarea>
看起来没有一个很好的答案,所以我想我会添加另一个可能的解决方案。
// Get the width of the input search field
const inputWidth = $event.path[0].clientWidth;
// If the input has content and the click is within 17px of the end of the search you must have clicked the cross
if ($event.target.value.length && ($event.offsetX < inputWidth && $event.offsetX > inputWidth - 17)) {
this.tableRows = [...this.temp_rows];
}
更新
const searchElement = document.querySelector('.searchField');
searchElement.addEventListener('click', event => {
// Get the width of the input search field
const inputWidth = $event.path[0].clientWidth;
// If the input has content and the click is within 17px of the end of the search you must have clicked the cross
if ($event.target.value.length && ($event.offsetX < inputWidth && $event.offsetX > inputWidth - 17)) {
this.tableRows = [...this.temp_rows];
}
});
在我的情况下,我不想使用JQuery和我的输入也是通用的,所以在某些情况下,它可以是类型“搜索”,但并不总是这样。我可以让它稍微延迟一点基于这里的另一个答案。基本上,我想在单击输入时打开一个组件,而不是在单击clear按钮时打开。
function onClick(e: React.MouseEvent<HTMLInputElement>) {
const target = e.currentTarget;
const oldValue = target.value;
setTimeout(() => {
const newValue = target.value;
if (oldValue && !newValue) {
// Clear was clicked so do something here on clear
return;
}
// Was a regular click so do something here
}, 50);
};
const inputElement = document.getElementById("input");
let inputValue;
let isSearchCleared = false;
inputElement.addEventListener("input", function (event) {
if (!event.target.value && inputValue) {
//Search is cleared
isSearchCleared = true;
} else {
isSearchCleared = false;
}
inputValue = event.target.value;
});
至少在Chrome中,搜索输入的“X”按钮似乎发出了一种不同的事件。
MDN上还声明可以触发InputEvent或Event: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/input_event
下面的测试。您将看到文本输入将是一个InputEvent,带有包含输入字符的“data”属性,单击X按钮将发出一个Event类型。
document.querySelector('input[type=search]').addEventListener('input', ev => console.log(ev))
因此,应能区分使用:
if (ev instanceof InputEvent) { ... }
你可以试试fuse.js。在基本配置中,可以通过搜索过滤到许多结果。但是在fuse实例的options对象中有很多调整搜索的可能性:https://fusejs.io/api/options.html
例如:阈值默认为0.6。如果你上升到1,它不会过滤任何东西。如果向下到0,结果中只有精确匹配。尝试一下这些设置。
这是一个在几分钟内实现的客户端搜索,在很多用例中已经足够了。
我还不如把我的5c也加进去。
keyup事件不检测鼠标单击X以清除字段,但输入事件检测击键和鼠标单击。您可以通过检查事件的originalEvent属性来区分触发输入事件的事件—它们之间有相当多的区别。
我发现最简单的方法如下:
jQuery("#searchinput").on("input",function(event) {
var isclick = event.originalEvent.inputType == undefined;
}
通过击键,event.originalEvent.inputType = "insertText"。
我使用Chrome -没有在其他浏览器中测试,但鉴于事件对象是相当普遍的,我猜这将在大多数情况下工作。
注意,仅仅单击输入不会触发事件。