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


当前回答

这里有一种方法。你需要添加增量属性到你的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>

其他回答

根据鲍安的回答,这是有可能的。前女友。

<head>
    <script type="text/javascript">
        function OnSearch(input) {
            if(input.value == "") {
                alert("You either clicked the X or you searched for nothing.");
            }
            else {
                alert("You searched for " + input.value);
            }
        }
    </script>
</head>
<body>
    Please specify the text you want to find and press ENTER!
    <input type="search" name="search" onsearch="OnSearch(this)"/>
</body>

实际上,每当用户搜索或单击“x”时,都会触发一个“search”事件。这特别有用,因为它理解“增量”属性。

现在,话虽如此,我不确定你是否能说出点击“x”和搜索之间的区别,除非你使用“onclick”黑客。不管怎样,希望这对你有所帮助。

多托罗网络参考

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

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

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