在HTML5中,搜索输入类型的右边会出现一个小X,这将清除文本框(至少在Chrome中,可能在其他浏览器中)。是否有一种方法来检测这个X在Javascript或jQuery中被点击,而不是检测盒子被点击或做一些位置点击检测(X -position/y-position)?


当前回答

我还不如把我的5c也加进去。

keyup事件不检测鼠标单击X以清除字段,但输入事件检测击键和鼠标单击。您可以通过检查事件的originalEvent属性来区分触发输入事件的事件—它们之间有相当多的区别。

我发现最简单的方法如下:

jQuery("#searchinput").on("input",function(event) {
      var isclick = event.originalEvent.inputType == undefined;
   }   

通过击键,event.originalEvent.inputType = "insertText"。

我使用Chrome -没有在其他浏览器中测试,但鉴于事件对象是相当普遍的,我猜这将在大多数情况下工作。

注意,仅仅单击输入不会触发事件。

其他回答

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);

应该能够适应这为大多数用途。

我想补充一个“晚”的答案,因为我今天在改变、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”)。

至少在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) { ... }

我的解决方案是基于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.");
},