【问题标题】:Focus on input inside modal causes ios to scroll down专注于模式内的输入导致ios向下滚动
【发布时间】:2016-10-16 13:56:02
【问题描述】:
我遇到了模态框内的输入问题。
当用户打开模态框时,它会覆盖整个页面,设置为高 z-index 和绝对位置。一旦用户关注模态框内的输入,在 ios 上,整个页面会出于某种原因向下滚动。
我认为向上滚动输入字段是为了给键盘留出一些空间是 ios 的行为,并且由于我的模式的 html 位于页面底部,它会尝试滚动到那个位置。
我已经尝试在 body 上使用 overflow-y: hidden 并在 touchmove 发生时将事件侦听器附加到 event.preventDefault() 上,当模式打开时,这些停止页面滚动,即使在 ios 上用户也无法滚动,但一次他们专注于一个输入,所有这些似乎都被忽略了。
【问题讨论】:
标签:
javascript
ios
html
forms
input
【解决方案1】:
This answer 为我工作。您需要做的另一件事是使输入中的文本大小至少为 16 像素,否则 iOS 会强制它执行烦人的“放大”功能。
如果您不想点击链接,也可以粘贴。
//Set 2 global variables
var scrollTopPosition = 0;
var lastKnownScrollTopPosition = 0;
//when the document loads
$(document).ready(function(){
//this only runs on the right platform -- this step is not necessary, it should work on all platforms
if( navigator.userAgent.match(/iPhone|iPad|iPod/i) ) {
//There is some css below that applies here
$('body').addClass('platform-ios');
//As you scroll, record the scrolltop position in global variable
$(window).scroll(function () {
scrollTopPosition = $(document).scrollTop();
});
//when the modal displays, set the top of the (now fixed position) body to force it to the stay in the same place
$('.modal').on('show.bs.modal', function () {
//scroll position is position, but top is negative
$('body').css('top', (scrollTopPosition * -1));
//save this number for later
lastKnownScrollTopPosition = scrollTopPosition;
});
//on modal hide
$('.modal').on('hidden.bs.modal', function () {
//force scroll the body back down to the right spot (you cannot just use scrollTopPosition, because it gets set to zero when the position of the body is changed by bootstrap
$('body').scrollTop(lastKnownScrollTopPosition);
});
}
});
css:
// You probably already have this, but just in case you don't
body.modal-open {
overflow: hidden;
width: 100%;
height: 100%;
}
//only on this platform does it need to be fixed as well
body.platform-ios.modal-open {
position: fixed;
}