在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 -没有在其他浏览器中测试,但鉴于事件对象是相当普遍的,我猜这将在大多数情况下工作。

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

其他回答

试试这个,希望能帮到你

$("input[name=search-mini]").on("search", function() {
  //do something for search
});

我相信这是唯一的答案,只有当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的答案)来工作。

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

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

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

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

这里有一种方法。你需要添加增量属性到你的html或它不会工作。

window.onload = function() { var tf = document.getElementById('textField'); var button = document.getElementById('b'); 按钮禁用 = 真; var onKeyChange = 函数 textChange() { 按钮禁用 = (tf.value === “”) ?真 : 假; } tf.addEventListener('keyup', onKeyChange); tf.addEventListener('search', onKeyChange); } <输入 id=“文本字段” 类型=“搜索” 占位符=“搜索” 增量=“增量”> <按钮 id=“b”>去!</button>