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


当前回答

看起来没有一个很好的答案,所以我想我会添加另一个可能的解决方案。

// 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];
}
});

其他回答

发现这篇文章,我意识到它有点老了,但我想我可能有一个答案。这处理点击十字,退格和按ESC键。我相信它可以写得更好——我对javascript还是个新手。下面是我最后做的——我使用jQuery (v1.6.4):

var searchVal = ""; //create a global var to capture the value in the search box, for comparison later
$(document).ready(function() {
  $("input[type=search]").keyup(function(e) {
    if (e.which == 27) {  // catch ESC key and clear input
      $(this).val('');
    }
    if (($(this).val() === "" && searchVal != "") || e.which == 27) {
      // do something
      searchVal = "";
    }
    searchVal = $(this).val();
  });
  $("input[type=search]").click(function() {
    if ($(this).val() != filterVal) {
      // do something
      searchVal = "";
    }
  });
});

点击TextField交叉按钮(X) onmousemove()被触发,我们可以使用这个事件来调用任何函数。

<input type="search" class="actInput" id="ruleContact" onkeyup="ruleAdvanceSearch()" placeholder="Search..." onmousemove="ruleAdvanceSearch()"/>

我相信这是唯一的答案,只有当x被点击。

然而,这有点俗气,ggutenberg的答案对大多数人都适用。

$('#search-field').on('click', function(){
  $('#search-field').on('search', function(){
    if(!this.value){
      console.log("clicked x");
      // Put code you want to run on clear here
    }
  });
  setTimeout(function() {
    $('#search-field').off('search');
  }, 1);
});

其中“#search-field”是输入的jQuery选择器。使用'input[type=search]'选择所有搜索输入。通过在单击字段后立即检查搜索事件(Pauan的答案)来工作。

对我来说,点击X应该算作一个更改事件是有意义的。我已经设置了onChange事件来做我需要它做的事情。所以对我来说,修复是简单地做这一行jQuery:

$('#search').click(function(){ $(this).change(); });

在我的情况下,我不想使用JQuery和我的输入也是通用的,所以在某些情况下,它可以是类型“搜索”,但并不总是这样。我可以让它稍微延迟一点基于这里的另一个答案。基本上,我想在单击输入时打开一个组件,而不是在单击clear按钮时打开。

function onClick(e: React.MouseEvent<HTMLInputElement>) {
  const target = e.currentTarget;
  const oldValue = target.value;
  setTimeout(() => {
    const newValue = target.value;
    if (oldValue && !newValue) {
      // Clear was clicked so do something here on clear
      return;
    }

    // Was a regular click so do something here
  }, 50);
};