解决 iOS Safari 浏览器上,给 <body>设置overflow hidden 仍然可以滑动的问题

735 阅读1分钟

问题

在下图场景(呼出左侧滑动菜单后)中,我们希望禁用 body 的滑动:

Untitled.gif

body 标签设置 overflow:hidden; 后,在 iOS 的 Safari 浏览器上仍然失效。

解决方案

const $body = document.querySelector('body');
let scrollPosition = 0;

export default {
  enable() {
    scrollPosition = window.pageYOffset;
    $body.style.overflow = 'hidden';
    $body.style.position = 'fixed';
    $body.style.top = `-${scrollPosition}px`;
    $body.style.width = '100%';
  },
  disable() {
    $body.style.removeProperty('overflow');
    $body.style.removeProperty('position');
    $body.style.removeProperty('top');
    $body.style.removeProperty('width');
    window.scrollTo(0, scrollPosition);
  }
};

注意,scrollPosition 要放在全局存储,disable 时拿到的 window.pageYOffset 已经是 0 了。