IOS 在输入焦点上显示键盘

新手上路,请多包涵

我有一个无法解决的问题。

IOS 上的 input.focus() 上不显示键盘

 searchMobileToggle.addEventListener('click', function() {
       setTimeout(function(){
          searchField.focus();
       }, 300);
    });

我一直在寻找没有结果的解决方案,我知道这是一个经常未解决的问题,但我看到 NIKE ( https://m.nike.com/fr/fr_fr/ ) 和 FOODSPRING ( https://www.foodspring .fr/ ) 在手机上进行。

所以我想知道他们是怎么做的?

原文由 Mibuko 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 433
2 个回答

我找到了一个解决方案, click() 没有用,但我想通了。

 searchMobileToggle.addEventListener('click', function() {
         if(mobileSearchblock.classList.contains('active')) {
            searchField.setAttribute('autofocus', 'autofocus');
            searchField.focus();
        }
        else {
            searchField.removeAttribute('autofocus');
        }
    });

我正在使用 vue.js,它在加载组件时删除了 input autofocus 属性。所以我点击它,但还有另一个问题,自动对焦只工作一次,但结合 focus(),它现在一直工作 :)

谢谢你的帮助 !

原文由 Mibuko 发布,翻译遵循 CC BY-SA 4.0 许可协议

其他答案都不适合我。我最终查看了 Nike javascript 代码,这就是我想出的可重用函数:

 function focusAndOpenKeyboard(el, timeout) {
  if(!timeout) {
    timeout = 100;
  }
  if(el) {
    // Align temp input element approximately where the input element is
    // so the cursor doesn't jump around
    var __tempEl__ = document.createElement('input');
    __tempEl__.style.position = 'absolute';
    __tempEl__.style.top = (el.offsetTop + 7) + 'px';
    __tempEl__.style.left = el.offsetLeft + 'px';
    __tempEl__.style.height = 0;
    __tempEl__.style.opacity = 0;
    // Put this temp element as a child of the page <body> and focus on it
    document.body.appendChild(__tempEl__);
    __tempEl__.focus();

    // The keyboard is open. Now do a delayed focus on the target element
    setTimeout(function() {
      el.focus();
      el.click();
      // Remove the temp element
      document.body.removeChild(__tempEl__);
    }, timeout);
  }
}

// Usage example
var myElement = document.getElementById('my-element');
var modalFadeInDuration = 300;
focusAndOpenKeyboard(myElement, modalFadeInDuration); // or without the second argument

请注意,这绝对是一个 hacky 解决方案,但 Apple 这么长时间没有解决这个问题这一事实证明了这一点。

原文由 n8jadams 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题