Javascript-移除滚动后,页面滚动到顶部

时间:2020-02-27 06:30:14

标签: javascript jquery css

当我显示/隐藏DIV时,我试图禁用和启用页面滚动。问题是当我删除滚动到顶部的滚动页时。我需要留在同一个地方。

CSS:

body {
    line-height: 1;
    font-size: 16px;
}

.restrict-body-scroll {
    overflow: hidden!important;
    position: relative;
    width: 100 %;
    height: 100 %;
    margin: 0;
}

.restrict-body-scroll.reserve-scroll-bar-gap {
    position: fixed;
    overflow - y: scroll!important;
}

preserve-sticky类用于导航菜单。

JS:

const scrollGapClass = 'reserve-scroll-bar-gap';
const preserveSticky = 'preserve-sticky';
let scrollTop = 0;

function disableBodyScroll() {
        addClass(findFirst('body', null), 'restrict-body-scroll');

        let globalBannerRect;
        let priceBannerRect;

        const globalBanner = findFirst('.global-banner', null);
        const priceBanner = findFirst('.price-banner', null);

        if (globalBanner) {
            globalBannerRect = globalBanner.getBoundingClientRect();
        }
        if (priceBanner) {
            priceBannerRect = priceBanner.getBoundingClientRect();
        }

        if ((document.documentElement.scrollTop || window.pageYOffset) > ((globalBannerRect) ? globalBannerRect.height : 0 || (priceBannerRect) ? priceBannerRect.height : 0)) {
            $('body').addClass(preserveSticky)
        }
        scrollTop = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop);
        $('body').css('top', -(document.documentElement.scrollTop || window.pageYOffset) + 'px').addClass(scrollGapClass);
}

function enableBodyScroll() {

    const isSafari = hasClass(findFirst('body'), 'safari');
    const isIpad = hasClass(findFirst('body'), 'iPad');

    removeClass(findFirst('body', null), 'restrict-body-scroll');
    $('body').removeClass(`${scrollGapClass} + ' ' + ${preserveSticky}`).removeAttr('style');
    if (isIpad || isSafari) {
        document.body.scrollTop = scrollTop;
    } else {
        document.documentElement.scrollTop = scrollTop;
    }
    scrollTop = 0;

}

function findFirst (selector, context) {
    return (context || document).querySelector(selector);
};

function addClass(el, className) {
    var classListSupport = checkClassListSupport();

    // check if the element is not null and classList is supported
    if (el && classListSupport) {
        el.classList.add(className);
    }

    // fallback for non-classlist supported browsers
    if (el && !classListSupport && !exports.hasClass(el, className)) {
        el.className += ' ' + className;
    }
};

function checkClassListSupport() {
    return 'classList' in document.documentElement ? true : false;
}

0 个答案:

没有答案
相关问题