Я пытался отключить и включить прокрутку страницы, когда я 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;
}