移动端聚焦输入框时禁止页面滚动的实现问题
解决输入框聚焦时页面自动滚动的问题
问题场景
开发西班牙语翻译游戏时,输入框位置已足够靠上,弹出虚拟键盘无需页面滚动,但聚焦输入框时页面仍会自动滚动,导致顶部关键信息被遮挡。尝试使用focus({preventScroll: true})方法未生效。
可行解决方案
方案1:临时锁定全局滚动
在输入框聚焦时固定页面滚动位置,失焦后恢复:
const GUESS_INPUT = document.getElementById("guess-input"); GUESS_INPUT.addEventListener('focus', () => { // 记录当前滚动坐标 const currentScroll = { top: window.pageYOffset || document.documentElement.scrollTop, left: window.pageXOffset || document.documentElement.scrollLeft }; // 强制页面保持当前滚动位置 window.onscroll = () => { window.scrollTo(currentScroll.left, currentScroll.top); }; }); GUESS_INPUT.addEventListener('blur', () => { // 解除滚动锁定 window.onscroll = null; });
方案2:禁用滚动锚定行为
浏览器的滚动锚定机制可能导致自动滚动,给输入框的父容器添加CSS属性阻止该行为:
.input-parent-container { overflow-anchor: none; }
方案3:自定义滚动+聚焦逻辑
先将输入框定位到视图内(避免不必要滚动),再执行聚焦:
const GUESS_INPUT = document.getElementById("guess-input"); // 仅在输入框完全不可见时才滚动到视图,否则保持原位 if (!isElementInViewport(GUESS_INPUT)) { GUESS_INPUT.scrollIntoView({ behavior: 'instant', block: 'nearest', inline: 'nearest' }); } GUESS_INPUT.focus(); // 辅助函数:判断元素是否在视图内 function isElementInViewport(el) { const rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && rect.right <= (window.innerWidth || document.documentElement.clientWidth) ); }
补充说明
preventScroll: true在部分移动端浏览器或复杂布局场景下存在兼容性问题,上述方案覆盖了更多边缘情况,可根据实际布局选择适配。
内容的提问来源于stack exchange,提问作者d50org
相关产品推荐
相关产品推荐

