在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?
当前回答
你也可以用一般的方式通过绑定onInput事件处理如下
<input type="search" oninput="myFunction()">
其他回答
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
根据鲍安的回答,这是有可能的。前女友。
<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>
看起来没有一个很好的答案,所以我想我会添加另一个可能的解决方案。
// 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];
}
});
实际上,每当用户搜索或单击“x”时,都会触发一个“search”事件。这特别有用,因为它理解“增量”属性。
现在,话虽如此,我不确定你是否能说出点击“x”和搜索之间的区别,除非你使用“onclick”黑客。不管怎样,希望这对你有所帮助。
多托罗网络参考
我想补充一个“晚”的答案,因为我今天在改变、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”)。
推荐文章
- 如何在JSON中使用杰克逊更改字段名
- CSS在特定的“内联块”项之前/之后换行
- 很好的初学者教程socket.io?
- 点击下载Href图片链接
- HtmlSpecialChars在JavaScript中等价于什么?
- 我如何删除背景图像在css?
- 如何克服HTML表单嵌套的限制?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 如何使Bootstrap 4卡在卡列相同的高度?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 使用域集图例引导