Scrolling to selected item when typing on iphone safari virtual keyboard

I am creating an iphone webapp and have a page with an input field. I would like the field to scroll up to the virtual keyboard when it appears. I tried putting scrollTo (x, y) on the input focal event (that is, just before the keyboard appears), but when I start typing, the page scrolls again (presumably based on the default mobile safari behavior). I also tried installing keypress event handlers, but preventing the propagation of these events simply turned off the keyboard, although this prevented scrolling.

Is there a way to force the page to be in a certain position (with an input field just above the keyboard) when the virtual keyboard appears, and not move it when I resume input?

+12
source share
3 answers

Good, so this is probably the worst hack you'll ever see, but nothing hits.

What you can do is change the position of the text field dynamically (using javascript) to a fixed position:fixed , this will change the position of the text field relative to the browser window, not the page. This should make the scroll of the Iphone irrelevant, and your text box should be at the top of the page no matter what. Then onBlur the css position is again set to relative (which should put it back in place).

To make it prettier, you can put the div behind the onFocus text box so that it hides the actual content of the site, and you could center the text box using the top and left css properties (just make sure they are cleared onBlur too).

+3
source

As far as I know, the problem is that when the keyboard starts, the browser tries to move the window into the field of view of the element itself.

What can happen is that the position of the scrollbar is recorded before the keyboard appears. The browser then calculates the distance that needs to be moved to the window in order to bring the item into view as soon as the keyboard pops up, based on the recorded value. After that, you changed the position of the window. Thus, it moves the window relative to the position you are setting, as opposed to the position in which it is thinking.

What behavior do you experience if you are not trying to scroll an element in the view manually (without creating scripts)?

It seems to me that the iPhone browser initially does what you want. If not, this may have something to do with positioning the elements. I.E. The browser cannot correctly calculate the position of an element, for example. If it is in a container with a fixed position (because it will move as soon as the browser tries to execute scollTo).

If this fails, try putting the scrollTo function in a timeout so that it works after the keyboard appears.

0
source

This may work, try using css translate3d instead of scrollTo (x, y)

See http://www.webkit.org/blog/386/3d-transforms/

-1
source

Source: https://habr.com/ru/post/954279/


All Articles