There are two main problems with soft keyboards on mobile terminals:

  • Soft keyboard pop-ups cause page layout confusion
  • On some form pages, you need to get focus and pop up a soft keyboard as soon as you enter the page

Let’s start with the first problem, as shown below

In some online solutions, when the soft keyboard pops up, the absolute positioning is changed to the relative positioning. After testing, this method does not work, because the height of the HTML element and the body element of the page is set to 100%. Therefore, when the soft keyboard pops up, the page will be compressed

There is another solution, this solution for Android models, listen to the window. Resize event in the page, this method is effective, the code is as follows

const htmlHeight = window.getComputedStyle(document.querySelector('html'), null).getPropertyValue('height').slice(0, - 2); Window.onresize = () => {// Determine the gap between the page height and the initial height. Const thisHeight = window.getComputedStyle(document.querySelector(' HTML '), null).getPropertyValue('height').slice(0, -2); If (htmlheight-thisheight > 140) {// If (htmlheight-thisheight > 140) {Copy the code

There is no unique way to get the height of a page. There is also a scheme for Ios, but it is not validated and doubtful. It listens for the focus and blur events of the input element and makes a show and hide judgment.

Look at the second problem, as soon as you enter the page, you get focus, and the soft keyboard automatically pops up.

Autofocus, el.click(), el.focus(), these methods are not compatible, but by my verification, these methods do not work!! (Is my phone bad?)

There’s only one way to do it

The soft keyboard is only valid for user – operated events

You can bind a click event to other elements and trigger the focus event in a callback function, but this may not work when the page has just finished loading, so you need to find a time point where the soft keyboard pops up. Rely on setTimeout to delay execution as follows

<html>
    <body>
        <label for="username"></label>
        <input id="username" />
    </body>
    <script>
        document.querySelector('label').onclick = (a)= > {
            document.querySelector('#username').focus();
        }
        setTimeout((a)= > {
            document.querySelector('label').click();
        }, 1000)
    </script>
</html>
Copy the code