问题
I have several <input type="number">
elements on my webpage. I'm using jQTouch, and I'm trying to stay fullscreen at all times; that is, horizontal scrolling is bad. Whenever I click an <input>
element, the page scrolls right, showing a black border on the right of the screen and de-centering everything. The inputs are offset from the left of the screen, and they begin somewhere toward the middle of the page.
How can I prevent this scrolling on focus?
回答1:
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!
回答2:
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.
回答3:
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');
});
回答4:
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
回答5:
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;" />
来源:https://stackoverflow.com/questions/2952782/preventing-an-input-element-from-scrolling-the-screen-on-iphone