IOS show keyboard on input focus

2020-03-24 09:05发布

问题:

I have a problem that i can't fix.

Keyboard doesn't show on input.focus() on IOS

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

I've been looking for a solution with no result, i know this is a frequently unsolved question but i see NIKE (https://m.nike.com/fr/fr_fr/) and FOODSPRING (https://www.foodspring.fr/) doing it on mobile.

So i'm wondering how do they do ?

回答1:

I found a solution, click() didn't work, but i figured it out.

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

I was working with vue.js that was removing input autofocus attribute, when the component was loaded. So i had it on click, but there was another problem, the autofocus only worked once, but combined with focus(), it now work all the time :)

Thanks for your help !



回答2:

None of the other answers worked for me. I ended up looking into the Nike javascript code and this is what I came up with as a reusable function:

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

Note that this is definitely a hacky solution, but the fact that Apple hasn't fixed this in so long justifies it.



回答3:

There is no legitimate way to do this since iOS kind of wants to only open the keyboard on a user interaction, however you can still achieve this with either using prompt() or using focus() from within a click() event it and will show up.