如何在iOS Safari中切换输入框时禁用自动滚动?
解决iOS 15输入框切换焦点时的滚动问题
以下是针对iOS 15环境验证有效的方案:
方案一:监听focus事件并阻止默认行为
给所有输入框绑定focus事件,触发时调用preventDefault(),同时可按需手动控制元素可视位置:
const inputs = document.querySelectorAll('input, textarea'); inputs.forEach(input => { input.addEventListener('focus', (e) => { e.preventDefault(); // iOS 15.4及以上版本可添加此参数,确保输入框可见但不触发页面滚动 input.scrollIntoView({ block: 'nearest', behavior: 'auto', preventScroll: true }); }); });
若需兼容iOS 15.0-15.3版本,可移除preventScroll参数,仅保留e.preventDefault()即可。
方案二:通过CSS锁定页面滚动
输入框聚焦时给body添加固定定位样式锁定滚动,失焦后恢复原滚动位置:
.body-lock { position: fixed; width: 100%; height: 100%; overflow: hidden; }
const inputs = document.querySelectorAll('input, textarea'); let scrollTop = 0; inputs.forEach(input => { input.addEventListener('focus', () => { scrollTop = window.pageYOffset; document.body.classList.add('body-lock'); document.body.style.top = `-${scrollTop}px`; }); input.addEventListener('blur', () => { document.body.classList.remove('body-lock'); window.scrollTo(0, scrollTop); }); });
方案三:禁用滚动容器的交互(针对自定义滚动容器场景)
如果页面使用了自定义滚动容器,可在输入框聚焦时临时禁用容器的滚动交互:
.scroll-container.no-scroll { pointer-events: none; overflow: hidden; }
const inputs = document.querySelectorAll('input, textarea'); const scrollContainer = document.querySelector('.scroll-container'); inputs.forEach(input => { input.addEventListener('focus', () => { scrollContainer.classList.add('no-scroll'); }); input.addEventListener('blur', () => { scrollContainer.classList.remove('no-scroll'); }); });
内容的提问来源于stack exchange,提问作者Иван Васильевич
相关产品推荐
相关产品推荐

