[英]Disable scrolling but keep the bar visible
When displaying a popup on a long page I need to disable scrolling. 在长页面上显示弹出窗口时,我需要禁用滚动。
I've tried 3 solutions but none are acceptable. 我已经尝试了3个解决方案,但没有一个可以接受。
document.body.style.position = 'fixed';
document.body.style.overflowY = 'scroll';
This could have been a good solution, but if I trigger the popup while having already scrolled to the end of the page, the page scrolls back to the top. 这本来可以是一个很好的解决方案,但是如果我在已经滚动到页面末尾时触发了弹出窗口,则页面会滚动回到顶部。
document.body.addEventListener("mousewheel", (e) => e.preventDefault());
This works but I can still click on the scrollbar and scroll. 这可行,但是我仍然可以单击滚动条并滚动。
document.body.style.overflow = 'hidden';
document.body.style.marginRight = '1rem';
This didn't add a margin. 这没有增加边际。 (and I'm afraid of the issues with different scrollbars width)
(而且我担心滚动条宽度不同的问题)
EDIT: 编辑:
I'm trying another solution based on HostListner 我正在尝试基于HostListner的另一种解决方案
@HostListener('window:scroll', ['$event'])
public handleScroll(event: any) {
console.log(event);
event.preventDefault();
}
It triggers correctly but doesn't prevent the scroll... 它可以正确触发,但不会阻止滚动...
Try to calculate the scrollbar width of the browser using 尝试使用以下方法计算浏览器的滚动条宽度
var scrollbarWidth = window.innerWidth - document.body.clientWidth;
And when popup is visible add overflow: hidden
to remove scrolling with margin-right
equal to the width of scrollbar so that the page does not jump using Object.assign
like 并在弹出窗口可见时添加
overflow: hidden
以取消以margin-right
等于滚动条宽度的滚动,以使页面不会像使用Object.assign
那样跳转
var scrollbarWidth = window.innerWidth - document.body.clientWidth;
Object.assign(document.body.style, {
overflow: "hidden",
marginRight: scrollbarWidth + "px"
});
>>> Note: Make sure your body has margin:0
by default >>> 注意: 默认情况下,请确保您的身体的
margin:0
var scrollbarWidth = window.innerWidth - document.body.clientWidth; Object.assign(document.body.style, { overflow: "hidden", marginRight: scrollbarWidth + "px" }); console.log(document.body.style.marginRight);
body { margin: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.