弹窗显示时滚动异常求助:滚动底层页面而非弹窗内容
Hey Laura! Let's get that popup scrolling working the way you want it. The core issue here is that when your popup is visible, the main page's scroll is still active—so any scrolling action affects the background instead of the popup's content. Here's a straightforward solution tailored to your code:
Step 1: Disable Background Scroll When Popup Opens
First, add a CSS class to lock the body's scroll when the popup is active. This prevents users from scrolling the background page while interacting with the popup.
Update your CSS with this:
/* Lock body scroll when popup is open */ body.no-scroll { overflow: hidden; /* Fix for iOS elastic scrolling behavior */ position: fixed; width: 100%; } /* Your existing popup styles (keep these, just add the tabindex line) */ .popup { width: 60%; position: fixed; height: 80%; top: 10%; left: 20%; background-color: white; box-shadow: 5px 5px 10px black; padding: 30px; overflow-y: scroll; z-index: 99; display: none; /* Allow popup to receive focus for keyboard scrolling */ tabindex: -1; }
Step 2: Update jQuery to Toggle Scroll Lock & Focus Popup
Modify your jQuery code to add/remove the scroll lock class when the popup opens/closes, and optionally focus the popup to ensure keyboard scrolling works correctly.
// Open popup on link click $('.anecdote-link').on('click', function(){ $('.mask').fadeIn(); // Lock background scroll $('body').addClass('no-scroll'); if ($(this).attr('id') == "show-BOA") { $('#popup-BOA').fadeIn(); // Focus the popup so keyboard scrolling targets it $('#popup-BOA').focus(); } }); // Handle popup close actions (close button and "Close" text) $('.popup .close, .text-close').on('click', function(){ $('.mask').fadeOut(); $(this).closest('.popup').fadeOut(); // Unlock background scroll $('body').removeClass('no-scroll'); });
Why This Works:
body.no-scroll: By settingoverflow: hidden, we prevent the main page from scrolling. Theposition: fixedfix ensures iOS devices don't exhibit unwanted elastic scrolling behavior.tabindex="-1": Makes your popup div focusable—this is key for keyboard users, as it ensures scroll actions (like arrow keys) target the popup instead of the background.- Focus on popup: When the popup opens, calling
.focus()directs user input (including scrolling) to the popup itself.
Quick Check:
Make sure your popup's content is tall enough to exceed the popup's height: 80%—otherwise, the scrollbar won't appear, and you might still think the scrolling isn't working!
内容的提问来源于stack exchange,提问作者LauraNMS

