在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?
当前回答
我的解决方案是基于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.");
},
其他回答
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;
});
搜索或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);
应该能够适应这为大多数用途。
至少在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) { ... }
最初的问题是“我能检测到点击‘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>
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
推荐文章
- 如何使一个DIV不包装?
- 使用jQuery以像素为整数填充或边距值
- CSS div元素-如何显示水平滚动条只?
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?
- JavaScript DOM删除元素
- 将dd-mm-yyyy字符串转换为日期
- Javascript复选框onChange
- Javascript函数前导bang !语法
- 如何在页面上遍历所有DOM元素?