Manually triggering the iPhone/iPad/iPod keyboard from JavaScript

后端 未结 7 1120
[愿得一人]
[愿得一人] 2020-11-28 12:34

I am developing an HTML code editor using simple DIV\'s and capturing events. When I use this on the iPad the keyboard never pops up since i\'m not technically in an editab

相关标签:
7条回答
  • 2020-11-28 13:02

    If your code is executed via something that was initiated via a user action then it will work.

    E.g;

    this works (pops keyboard):

    <input type='text' id='foo'><div onclick='$("#foo").focus();'>click</div>
    

    this doesn't work (input gets a border but no keyboard pop):

    <input type='text' id='foo'>
    <script>
      window.onload = function() {
        $("#foo").focus();
      }
    </script>
    
    0 讨论(0)
  • 2020-11-28 13:02

    Place a transparent textarea over the contentEditable div. The keyboard will open, as soon as the user focus the textarea.

    Register an event listener on the textarea for the focus event and set the visibilityof the textarea to hidden. This prevents the blinking cursor.

    Set the visibility of the textarea back to visible after the blur event occurred.

    Register additional event listeners for keydown, keyup, keypressevents and process theses events the same way, as you process them in the contentEditable div.

    0 讨论(0)
  • 2020-11-28 13:03

    I have found that calling prompt("Enter some value") does trigger the keyboard on my iPad 2. Not sure if this is helpful in your situation or not.

    0 讨论(0)
  • 2020-11-28 13:03

    Proxy input trick

    I figured out another dirty workaround, but works well. The trick is based on the fact, that if the keyboard is already open, changing the focus will not close the keyboard.

    1. Add a small "proxy invisible input" in top left of the page with position fixed (the fixed position prevents the flicker, also make sure that the field has font-size bigger than 16px to prevent iOS page zoom on focus)
    2. On clicking the button, just .focus() on this invisible field. The keyboard will open...
    3. Show or render your other input fields
    4. Now with the keyboard open just .focus() on the desired input. You can use small setTimeout delay, for example 500ms if needed
    0 讨论(0)
  • 2020-11-28 13:08

    The answers to this questions suggest that it's not possible: Why doesn't @contenteditable work on the iPhone?

    A colleague of mine who was working on a similar project ended up using a textarea for the iPad version of his editor, and contenteditable divs/spans for browsers that support contenteditable. Perhaps something similar would work for you.

    0 讨论(0)
  • 2020-11-28 13:18

    Here's a solution for you:

    <input id="my-input" type="text" />
    
    <script type="text/javascript">
        var textbox = document.getElementById('my-input');
        textbox.select();
    </script>
    
    0 讨论(0)
提交回复
热议问题