【问题标题】:Prevent input datalist from automatically opening upon receiving initial keyboard focus防止输入数据列表在收到初始键盘焦点后自动打开
【发布时间】:2015-10-17 06:52:52
【问题描述】:

我有一个 HTML5 下拉控件,配置类似于:

<input id="textCtrl" list="browsers">

<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

我还将这个控件的焦点放在页面加载事件上:

//It's done via JQuery, but it makes no difference for this question
$(function () {
    //Set focus to the text control
    $('#textCtrl').focus();
};

所以发生的情况是,当页面在 IE 中加载时,或者在 Windows 10 中调用的任何页面时,下拉列表会在页面加载时自动打开,这看起来有点奇怪。所以我想保持它最初关闭:

在这里,你可以自己try it

那么,当文本输入具有初始键盘焦点时,有什么方法可以避免在页面加载时打开此列表?

【问题讨论】:

    标签: html internet-explorer input html-datalist


    【解决方案1】:

    不是一个理想的答案,但以下对我有用:

    // Temporarily remove the list from the input and set focus
    $("#textCtrl").removeAttr("list").focus();
    
    // Restore the list to the input - if this is done immediately
    // the datalist is shown on focus so use a timer to delay adding
    // the list.
    setTimeout(function() {
        $("#textCtrl").attr("list","browser");
    },1);
    

    【讨论】:

      猜你喜欢
      • 2020-11-11
      • 2013-08-02
      • 1970-01-01
      • 2017-03-14
      • 2011-05-25
      • 2017-04-23
      • 2020-07-30
      • 2012-04-01
      相关资源
      最近更新 更多