简体   繁体   中英

How to remove jank from overflow:hidden?

I have a modal that changes my body to overflow:hidden when clicked. This removes the scrollbar so my page wont scroll. When you close the modal, my body changes back to overflow:auto and the page can scroll again. This is done with two simple functions I set in my Javascript.

function hidden() {
    document.querySelector("body").style.overflow = "hidden";
}

function show() {
    document.querySelector("body").style.overflow = "auto";
}

However, there's some jank involved where you can see my entire page move to the right when the scrollbar is removed. Is there any way I can fix this to not look so bad? Or perhaps there's a different way to disable scrolling when the modal is up?

You could disable scrolling while keeping the scrollbar with a JS event listener to intercept scroll events like this:

const ignoreScroll = (e) => {
    e.preventDefault();
};

// Add scrolling block
document.addEventListener('scroll', ignoreScroll);
document.addEventListener('mousewheel', ignoreScroll);
document.addEventListener('touchmove', ignoreScroll);

// Remove scrolling block
document.removeEventListener('scroll', ignoreScroll);
document.removeEventListener('mousewheel', ignoreScroll);
document.removeEventListener('touchmove', ignoreScroll);

You could also programmatically apply the touch-action: none CSS rule to disable scrolling on an element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM