How to prevent iOS keyboard from pushing the view off screen with CSS or JS

北城以北 提交于 2019-12-03 11:37:31

问题


I have a responsive web page that opens a modal when you tap a button. When the modal opens, it is set to take up the full width and height of the page using fixed positioning. The modal also has an input field in it.

On iOS devices, when the input field is focused, the keyboard opens. However, when it opens, it actually pushes the full document up out of the way such that half of my page goes above the top of the viewport. I can confirm that the actual html tag itself has been pushed up to compensate for the keyboard and that it has not happened via CSS or JavaScript.

Has anyone seen this before and, if so, is there a way to prevent it, or reposition things after the keyboard has opened? It's a problem because I need users to be able to see content at the top of the modal while, simultaneously, I'd like to auto-focus the input field.


回答1:


first

<script type="text/javascript">
 $(document).ready(function() {
     document.ontouchmove = function(e){
          e.preventDefault();
          }
 });

then this

input.onfocus = function () {
    window.scrollTo(0, 0);
    document.body.scrollTop = 0;
}



回答2:


For anyone stumbling into this in React, I've managed to fix it adapting @ankurJos solution like this:

const inputElement = useRef(null);

useEffect(() => {
  inputElement.current.onfocus = () => {
    window.scrollTo(0, 0);
    document.body.scrollTop = 0;
  };
});

<input ref={inputElement} />



回答3:


you could also do this if you don't want scrollTo the top(0, 0)

window.scrollBy(0, 0)



回答4:


Both IOS8 and Safari bowsers behave the same for input.focus() occuring after page load. They both zoom to the element and bring up the keyboard.(Not too sure if this will be help but have you tried using something like this?)

HTML IS

<input autofocus>

JS is

for (var i = 0; i < 5; i++) {
document.write("<br><button onclick='alert(this.innerHTML)'>" + i + "</button>");
}

//document.querySelector('input').focus();

CSS

button {
width: 300px;
height: 40px;
}

ALso you will have to use a user-agent workaround, you can use it for all IOS versions

if (!/iPad|iPhone|iPod/g.test(navigator.userAgent)) {
element.focus();
}



回答5:


In some situations this issue can be mitigated by re-focusing the input element.

input.onfocus = function () {
  this.blur();
  this.focus();
}


来源:https://stackoverflow.com/questions/38619762/how-to-prevent-ios-keyboard-from-pushing-the-view-off-screen-with-css-or-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!