Preventing an <input> element from scrolling the screen on iPhone?

北城余情 提交于 2019-11-28 05:00:42
Mischa Magyar

I just found the solution to this problem in this post Stop page scrolling from focus

Just add onFocus="window.scrollTo(0, 0);" to your input field and you're done! (Tried it with <textarea> and <input type="text" /> on the iPad, but I'm pretty sure it'll work on the iPhone too.)

I was afraid the scrolling would be visible as a flicker or something, but fortunately that is not the case!

here is how I solved this on the iPhone (mobile Safari) (I used jQuery)

1) create a global variable that holds the current scroll position, and which is updated every time the user scrolls the viewport

var currentScrollPosition = 0;
$(document).scroll(function(){
    currentScrollPosition = $(this).scrollTop();
});

2) bind the focus event to the input field in question. when focused, have the document scroll to the current position

$(".input_selector").focus(function(){
    $(document).scrollTop(currentScrollPosition);
});

Ta Da! No annoying "scroll on focus"

One thing to keep in mind...make sure that the input field is ABOVE the keypad, else you will hide the field. That can be easily mitigated by adding an if-clause.

cacheflowe

I would recommend using the jQuery.animate() method linked to above, not just the window.scrollTo(0,0), since iOS animates the page offset properties when an input element is focused. Calling window.scrollTo() just once may not work with the timing of this native animation.

For more background, iOS is animating the pageXOffset and pageYOffset properties of window. You can make a conditional check on these properties to respond if the window has shifted:

if(window.pageXOffset != 0 || window.pageYOffset != 0) {
  // handle window offset here
}

So, to expand on the aforementioned link, this would be a more complete example:

$('input,select').bind('focus',function(e) { 
  $('html, body').animate({scrollTop:0,scrollLeft:0}, 'slow'); 
});

If the focus is being set programmatically, this is what I would do:

Save the window's scollTop value before changing the focus. Then restore the scrollTop to the saved value immediately after setting focus.

If using jQuery:

var savedScrollTop = $(document).scrollTop(); // save scroll position
<code that changes focus goes here>
$(document).scrollTop(savedScrollTop ); // restore it

Try this, i think the problem is the zoom:

<meta name="viewport" content="width=device-width;initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!