如何在position: fixed定位的Div移出页面时实现页面可滚动(同步滚动场景下不改变Div定位)
Got it, let's work through this problem. The key issue here is that your .div2 is fixed-positioned, which means it doesn't affect the page's scrollable area. So when it moves outside the viewport as .div1 scrolls, the page won't let you scroll to see it—even though we can't change .div2's position property, we can adjust the page's scrollable height dynamically to fix this.
Here's the step-by-step fix:
Step 1: Adjust Base CSS
First, let's set a base style for the body to avoid default margins and ensure it starts with at least the viewport height:
body { margin: 0; min-height: 100vh; } .div1 { background-color: blue; width: 100px; height: 300px; overflow-y: auto; position: fixed; } .div2 { background-color: red; width: 100px; position: fixed; top: 600px; left: 130px; }
Step 2: Modify JavaScript to Manage Page Scroll Height
We need to dynamically update the page's minimum height whenever .div2 moves, so the page extends far enough to let users scroll to see it. Here's the updated JS:
var main = document.querySelector('.div1'); var target = document.querySelector('.div2'); var target_offsetTop = target.getBoundingClientRect().top; var targetHeight = target.offsetHeight; var viewportHeight = window.innerHeight; // Function to update page's minimum height based on div2's position function updatePageMinHeight(targetTop) { // Calculate the bottom position of div2 var targetBottom = targetTop + targetHeight; // Set body's min-height to the larger of targetBottom or viewport height document.body.style.minHeight = Math.max(targetBottom, viewportHeight) + 'px'; } // Initialize page height on load updatePageMinHeight(target_offsetTop); main.onscroll = function () { var main_scrollStart = main.scrollTop; var targetCurrentTop = target_offsetTop + main_scrollStart; target.style.top = targetCurrentTop + 'px'; // Update page height every time div1 scrolls updatePageMinHeight(targetCurrentTop); } // Handle window resize to recalculate viewport and page height window.addEventListener('resize', function() { viewportHeight = window.innerHeight; var currentTargetTop = parseInt(target.style.top) || target_offsetTop; updatePageMinHeight(currentTargetTop); });
How This Works
- Dynamic Page Height: The
updatePageMinHeightfunction calculates where.div2ends (top position + its height). If this bottom position is below the viewport, we set the body'smin-heightto this value—this forces the page to have enough scrollable space to reveal.div2. - Initial Setup: We call the function once on load to make sure the page starts with the correct height even before scrolling.
- Resize Handling: The window resize listener ensures the page adjusts correctly if the user changes their window size.
This keeps .div2's position: fixed intact, maintains the sync scrolling with .div1, and lets the page scroll to reveal .div2 whenever it moves outside the viewport.
内容的提问来源于stack exchange,提问作者user14982116

