页面禁止滚动和恢复滚动

724 阅读1分钟

应用场景

当打开一些具有背景遮罩层的组件或内容,类似于弹窗、协议、提示,或者弹出一个广告时我们希望在弹窗打开的时候页面禁止滑动,在弹窗关闭的时候页面恢复滚动。

实现方法


let bodyScrollFlag, historyScrollTop;

/**
 * @method disablePageScroll
 * @desc 记录页面的历史位置,并禁止页面滑动
 */
export function disablePageScroll() {
    bodyScrollFlag = true;
    if (document.body.scrollTop) {
        historyScrollTop = document.body.scrollTop;
    } else {
        bodyScrollFlag = false;
        historyScrollTop = document.documentElement.scrollTop;
    }

    document.body.setAttribute('style', `
            overflow: hidden; 
            position: fixed;
            top: -${ historyScrollTop }px
            `
    );
}

/**
 * @method revertPageScroll
 * @desc 移除页面的禁止滑动,是页面恢复滑动
 */
export function revertPageScroll() {
    document.body.setAttribute('style', ``);

    if (!historyScrollTop && historyScrollTop !== 0) {
        return;
    }

    // 回到历史滑动位置
    if (bodyScrollFlag) {
        document.body.scrollTop = historyScrollTop;
    } else {
        document.documentElement.scrollTop = historyScrollTop;
    }
}