【问题标题】:Maintain colllapse-state after refresh刷新后保持折叠状态
【发布时间】:2020-03-13 15:02:58
【问题描述】:

在我的侧边栏中,我添加了一个折叠按钮来显示/隐藏表单。现在我想在刷新页面时保持折叠状态: 如果表单在刷新页面之前未折叠,则刷新后必须保持这种状态。

我认为我需要在 JavaScript 中使用 localStorage,但我实际上不知道如何使用它。

这是我的 HTML:

<!-- Sidebar -->
    <ul class="sidebar navbar-nav">
         <li class="nav-item active">
                  <a class="nav-link" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample">
                      <i class="fa fa-filter"></i>
                      <span>Search Filter</span>
                  </a>
          </li>


 </ul>

<!-- Form -->
<div class="collapse" id="collapseExample">
<form>
......
</form>

我只找到了一些代码,但它似乎对我不起作用..:

var shown = []

// On collapse
shown.remove($(this).attr('id'));
localStorage.setItem('shown', shown);

// On open
shown.push($(this).attr('id'));
localStorage.setItem('shown', shown);

// On page load
var shown = localStorage.getItem('shown');
for (var s in shown) {
    $('#collapseExample' + s).show(); 
}

感谢您的帮助!

【问题讨论】:

    标签: javascript html toggle collapse


    【解决方案1】:

    这是一个有效的 Bootstrap 4 折叠示例。与起始模板的主要区别在于,我将 jQuery 导入移至文件顶部,以便可以使用 document.load 函数。我已将 cmets 添加到代码中,但如果仍有不清楚的地方,请继续提问。请注意,我为历史 cmets 留下了 vanilla javascript 答案,以防它也对您有所帮助。

    我从这里使用了起始页: https://getbootstrap.com/docs/4.0/getting-started/introduction/

    这里的第一个折叠示例: https://getbootstrap.com/docs/4.0/components/collapse/

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <!-- Required meta tags -->
        <meta charset="utf-8" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
    
        <!-- Bootstrap CSS -->
        <link
          rel="stylesheet"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
          crossorigin="anonymous"
        />
    
        <title>Hello, world!</title>
        <!-- jQuery -->
        <script
          src="https://code.jquery.com/jquery-3.2.1.slim.min.js"
          integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
          crossorigin="anonymous"
        ></script>
        <script>
          $(function() {
            // store a reference to the collapse div so that 
            // we don't have to keep looking it up in the dom
            const collapseExample = $("#collapseExample");
    
            // register a callback function to the collapse div that
            // will be called every time the collapse is opened.
            collapseExample.on("shown.bs.collapse", function() {
                // since we know that that this function is called on
                // open, we'll set the localStorage value to "show" 
                localStorage.setItem("collapseExample", "show");
            });
    
            // register a callback function to the collapse div that
            // will be called every time the collapse is closed.
            collapseExample.on("hidden.bs.collapse", function() {
                // since we know that that this function is called on
                // open, we'll set the localStorage value to "hide" 
                localStorage.setItem("collapseExample", "hide");
            });
    
            // Since this function runs on page load (meaning only once), we can
            // check the value of localStorage from here and then call the
            // bootstrap collapse methods ourselves:
    
            // Check the value of the localStorage item
            const showExampleCollapse = localStorage.getItem("collapseExample");
    
            // Manipulate the collapse based on the value of the localStorage item.
            // Note that the value is determined by lines 36 or 44. If you change those,
            // then make sure to check that the comparison on the next line is still valid.
            if (showExampleCollapse === "show") {
                collapseExample.collapse("show");
            } else {
                collapseExample.collapse("hide");
            }
          });
        </script>
      </head>
      <body>
        <main>
          <p>
            <a
              class="btn btn-primary"
              data-toggle="collapse"
              href="#collapseExample"
              role="button"
              aria-expanded="false"
              aria-controls="collapseExample"
            >
              Link with href
            </a>
            <button
              class="btn btn-primary"
              type="button"
              data-toggle="collapse"
              data-target="#collapseExample"
              aria-expanded="false"
              aria-controls="collapseExample"
            >
              Button with data-target
            </button>
          </p>
          <div class="collapse" id="collapseExample">
            <div class="card card-body">
              Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus
              terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer
              labore wes anderson cred nesciunt sapiente ea proident.
            </div>
          </div>
        </main>
    
        <!-- Optional JavaScript -->
        <!-- Popper.js, then Bootstrap JS -->
        <script
          src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
          integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
          crossorigin="anonymous"
        ></script>
        <script
          src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
          integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
          crossorigin="anonymous"
        ></script>
      </body>
    </html>
    
    

    结束引导回答

    开始香草 JAVASCRIPT 答案

    这是您似乎正在尝试做的一个基本的、独立的版本。它不漂亮,但希望它很清楚。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <script>
        function getCollapsed() {
            const state = localStorage.getItem('collapsed');
            if(state === 'collapsed'){
                return true;
            }
            return false;
        }
        function getStatus(){
            const resultDiv = document.getElementById('result');
            const isCollapsed = getCollapsed();
            if(isCollapsed){
                resultDiv.innerHTML = "collapsed";
            }else{
                resultDiv.innerHTML = "un-collapsed";
            }
        }
        function toggleCollapse(){
            const isCollapsed = getCollapsed();
            if(isCollapsed){
                localStorage.setItem('collapsed', 'un-collapsed');
            }else{
                localStorage.setItem('collapsed', 'collapsed');
            }
            getStatus();
        }
        </script>
    </head>
    <body onload="getStatus()">
        <div>
            <button onclick="toggleCollapse()">Toggle Collapse</button>
        </div>
        <div id="result"></div>
    </body>
    </html>
    

    【讨论】:

    • 由于您似乎正在使用引导程序,我将在几分钟后使用引导程序折叠示例对其进行更新。
    • 非常感谢!我将您的代码包含在我的代码中,仅将 id 从“result”调整为“collapseExample”。提交表单时知道使用 onclick="toggleCollapse()" 函数。但它仍然不起作用......你知道出了什么问题吗?非常感谢!!!!
    • @alipfi:我将使用 bootstrap 4 中的默认启动器及其第一个折叠组件示例来编辑此答案。这个应该有更多帮助。我将把第一个留在帖子底部,但它们实际上是 2 个不同的答案。
    • 您能帮我解决我的第二期问题吗? stackoverflow.com/questions/58876694/… 刷新页面时,我试图保存表单的复选框状态。我还没有找到合适的解决方案...提前感谢
    • @alipfi:当你有机会了解它为什么起作用时,请确保你花一些时间。然后你也可以帮助别人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 2019-05-19
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多