【问题标题】:Closing an HTML datalist dropdown on enter在输入时关闭 HTML 数据列表下拉列表
【发布时间】:2019-08-03 18:47:37
【问题描述】:

我有一个用于从列表中选择项目的数据列表。我希望数据列表下拉菜单在以下情况下关闭:

  1. 用户输入选项的确切名称并按回车键,或者
  2. 用户单击数据列表下拉列表中的项目。

同时支持 Firefox 和 Chrome (2)。 Firefox 还支持按回车键关闭下拉菜单。但是,键入选项并按 Enter 不会关闭 Chrome 中的下拉菜单。

Firefox 在 Chrome 中的行为是否可能,必要时使用 Javascript?

我唯一的想法是blur datalist 输入,但下拉菜单在 Chrome 中保持打开状态。

如果相关,我正在运行 Firefox 68 和 Chrome 75。

【问题讨论】:

  • 你找到答案了吗?

标签: javascript html html-datalist


【解决方案1】:

今天遇到了这个。你的想法很接近,在 Chrome 80 中对我有用的是 blur 输入。

<input type="list" id="itemInput" list="itemList"/>
<datalist id="itemList">
  <option value="item1"/>
  <option value="item2"/>
  <option value="item3"/>
</datalist>
function selectedOption(value) {
  let selected;
// see if there a matching item, ignoring case
  itemList.childNodes.forEach(function(option) {
    if (option.value.toLowerCase() === value.toLowerCase())
      selected = option;
  });
  return selected;
}

itemInput.addEventListener('keypress', function(ev) {
  if (ev.key === 'Enter') {
    const text = itemInput.value;
    const selected = selectedOption(text);
    if (selected) {
// we may have matched on different insensitive case, so set the actual value
      itemInput.value = selected.value;
// blur the input to close the datalist popup
      itemInput.blur();
    }
  }
});

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多