You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现桌面端50%、移动端100%宽度的侧边面板?

Responsive Side Panel Adjustment

Hey Sourav! Let's get that side panel to behave exactly how you want—taking up 100% of the viewport on mobile and 50% on desktop. Here's a simple, effective way to update your code:

Updated JavaScript Functions

We'll modify the openNav() function to check the current screen size before setting the panel width. We'll also add an optional resize handler to adjust the panel if the window is resized while it's open:

function openNav() {
  const sidePanel = document.getElementById("mySidecmnt");
  // Define our mobile breakpoint (768px is a standard, feel free to adjust)
  const isMobileViewport = window.innerWidth < 768;
  // Set width based on viewport
  sidePanel.style.width = isMobileViewport ? "100%" : "50%";
}

function closeNav() {
  document.getElementById("mySidecmnt").style.width = "0";
}

// Optional: Auto-adjust panel width when window is resized
window.addEventListener('resize', () => {
  const sidePanel = document.getElementById("mySidecmnt");
  // Only adjust if the panel is currently open
  if (sidePanel.style.width !== "0") {
    const isMobileViewport = window.innerWidth < 768;
    sidePanel.style.width = isMobileViewport ? "100%" : "50%";
  }
});

To make the panel's open/close action feel polished, add this CSS to your stylesheet. It ensures a smooth transition and sets up the panel's fixed positioning:

.sidecmnt {
  position: fixed;
  top: 0;
  right: 0; /* Change to left if you want the panel on the other side */
  height: 100vh;
  width: 0;
  overflow-x: hidden;
  transition: width 0.3s ease-in-out; /* Smooth width transition */
  background-color: #ffffff; /* Replace with your preferred background */
  padding: 2rem;
  box-sizing: border-box;
  z-index: 1000; /* Ensure it sits above other content */
}

.closebtnsty {
  display: inline-block;
  margin-bottom: 1.5rem;
  cursor: pointer;
}

How This Works

  • The openNav() function checks the viewport width using window.innerWidth. If it's under 768px (our mobile breakpoint), it sets the panel to 100% width; otherwise, 50%.
  • The resize listener ensures that if the user resizes their window while the panel is open, the width adjusts automatically to match the new viewport size.
  • The CSS transition adds a smooth animation when the panel opens or closes, making the experience feel much more professional.

内容的提问来源于stack exchange,提问作者Sourav Pan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:31:21