如何防止高度变化导致侧边栏关闭?求可行代码方案
Got it, let's break down why this is happening first. Your fitContent() function runs every time the window resizes—including when the height changes (like when the mobile keyboard pops up or you adjust the viewport height in dev tools). Right now, if the window width is under 1366 (which it always is on mobile), it calls closeRightSide() unconditionally, regardless of whether the sidebar was open or not. That's why it keeps closing on height changes.
Here are a couple of solid solutions to fix this:
Solution 1: Only Trigger Sidebar Toggle on Width Changes
This approach tracks the last known window width and only adjusts the sidebar state if the width actually changes (ignoring height-only resizes).
First, declare a variable outside your function to store the last width:
let lastWindowWidth = window.innerWidth;
Then modify your fitContent() function:
function fitContent() { // Keep your existing layout adjustment logic var top = $(window).scrollTop() < 340 ? 270 - $(window).scrollTop() : 0; rightSide.css("top", top + "px"); content.css("min-height", window.innerHeight - 130 + "px"); const currentWindowWidth = window.innerWidth; // Only handle sidebar toggle if width changed by more than 1px (to avoid false positives) if (Math.abs(currentWindowWidth - lastWindowWidth) > 1) { if (currentWindowWidth < 1366) { closeRightSide(); } else { openRightSide(); } // Update the last width after handling the change lastWindowWidth = currentWindowWidth; } }
Solution 2: Don't Force Close Sidebar on Mobile (Recommended for User Experience)
If your mobile sidebar is meant to be toggled manually by users, you can remove the forced close logic for small screens entirely. This way, once a user opens the sidebar, it stays open even if the viewport height changes.
Modify fitContent() like this:
function fitContent() { // Keep your existing layout adjustment logic var top = $(window).scrollTop() < 340 ? 270 - $(window).scrollTop() : 0; rightSide.css("top", top + "px"); content.css("min-height", window.innerHeight - 130 + "px"); var window_Width = window.innerWidth; // Only force the sidebar open on large screens if (window_Width >= 1366) { openRightSide(); } // No forced close on small screens—let the user's toggle actions control the state }
Why These Work
- Solution 1 ensures that height-only resizes (like keyboard popups) don't trigger the sidebar close logic, while still handling proper sidebar state when the screen width changes (e.g., rotating a phone from portrait to landscape).
- Solution 2 gives mobile users full control over the sidebar—they open it when they want, and it stays open until they manually close it, which is more intuitive for mobile interactions.
内容的提问来源于stack exchange,提问作者DohaHelmy

