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


当前回答

我知道这是一个老问题,但我一直在寻找类似的东西。确定点击“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);
});

其他回答

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

你似乎不能在浏览器中访问它。搜索输入是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
  }
});

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