在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?
当前回答
完整的解决方案在这里
这将在单击搜索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();
}
}
});
欢呼。
其他回答
我还不如把我的5c也加进去。
keyup事件不检测鼠标单击X以清除字段,但输入事件检测击键和鼠标单击。您可以通过检查事件的originalEvent属性来区分触发输入事件的事件—它们之间有相当多的区别。
我发现最简单的方法如下:
jQuery("#searchinput").on("input",function(event) {
var isclick = event.originalEvent.inputType == undefined;
}
通过击键,event.originalEvent.inputType = "insertText"。
我使用Chrome -没有在其他浏览器中测试,但鉴于事件对象是相当普遍的,我猜这将在大多数情况下工作。
注意,仅仅单击输入不会触发事件。
试试这个,希望能帮到你
$("input[name=search-mini]").on("search", function() {
//do something for search
});
看起来没有一个很好的答案,所以我想我会添加另一个可能的解决方案。
// 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时清除搜索。 或 当用户按回车键时,将调用搜索API。 这段代码可以通过附加的esc键up事件匹配器进一步扩展。但是这个应该能搞定。
document.getElementById("userSearch").addEventListener("search",
function(event){
if(event.type === "search"){
if(event.currentTarget.value !== ""){
hitSearchAjax(event.currentTarget.value);
}else {
clearSearchData();
}
}
});
欢呼。
你似乎不能在浏览器中访问它。搜索输入是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
}
});
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求