如何配置默认启用的基于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 returnfalseon first visit (sincelocalStoragehas no value yet), hiding the sidebar. We changed it tolocalStorage.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'sclickedclass 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
localStoragevalue is stored as a string ("true"or"false"), so our initial check accounts for that string comparison to avoid unexpected behavior.
内容的提问来源于stack exchange,提问作者Dest
相关产品推荐
相关产品推荐

