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

如何配置默认启用的基于localStorage的显示/隐藏JS脚本

Hey folks, let's fix up this localStorage-powered sidebar show/hide script to meet your "default visible" requirement. The original code had a tiny logic quirk that would hide the sidebar on first load, so here's the adjusted version plus a breakdown of how everything works:

Adjusted Working Code
$(document).ready(function () {
    // 默认可见:仅当localStorage明确存了'false'时才隐藏
    var sidebarVisible = localStorage.getItem('sidebar') !== 'false';
    $('#sidebar').toggle(sidebarVisible);
    $('.bgcontainer_center').toggleClass('clicked', sidebarVisible);

    $("#toggle").click(function () {
        $("#sidebar").toggle("slow", function () {
            // 切换完成后,将当前可见状态存入localStorage
            localStorage.setItem('sidebar', $('#sidebar').is(':visible'));
        });
        $(".bgcontainer_center").toggleClass('clicked');
    });
});
What's Changed & Why
  • Default Visibility Fix: The original check localStorage.getItem('sidebar') == 'true' would return false on first visit (since localStorage has no value yet), hiding the sidebar. We changed it to localStorage.getItem('sidebar') !== 'false' so the sidebar starts visible unless we've explicitly stored a 'false' state.
  • Smooth Toggle Animation: The toggle("slow") method adds a smooth transition when showing/hiding the sidebar, making the interaction feel more polished.
  • State Persistence: After each toggle completes, we save the sidebar's current visibility state to localStorage—so when the user refreshes the page, their preferred state is restored automatically.
  • Sync Container Class: We keep the .bgcontainer_center's clicked class in sync with the sidebar's visibility, which is handy if you're using that class for layout adjustments (like shifting main content when the sidebar hides).
Quick Notes
  • Make sure jQuery is loaded before this script runs, otherwise the $ functions won't work!
  • The localStorage value is stored as a string ("true" or "false"), so our initial check accounts for that string comparison to avoid unexpected behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:34:01