在页面刷新/导航时保留 Twitter Bootstrap 折叠状态

Posted

技术标签:

【中文标题】在页面刷新/导航时保留 Twitter Bootstrap 折叠状态【英文标题】:Retain Twitter Bootstrap Collapse state on Page refresh/Navigation 【发布时间】:2012-09-25 20:12:02 【问题描述】:

我正在使用 Bootstrap 的“折叠”插件来为一长串链接制作手风琴。手风琴正文标签包括“折叠”,因此当页面加载时所有组都被折叠。当您打开一个组并单击一个链接时,它会将您带到一个新页面以查看一些详细信息,然后您单击一个返回链接或浏览器返回以返回到列表。不幸的是,当您返回手风琴时,手风琴又回到了折叠状态,您必须再次打开该组并找到您所在的位置。我预计会有很多这种来回导航,这种行为会令人沮丧。

有什么方法可以保留用户的位置并返回到它,或者只是阻止页面重新加载或 javascript 再次触发。

我认为解决方案可能是沿着这些思路,但不确定。 Twitter bootstrap: adding a class to the open accordion title

【问题讨论】:

您是否考虑过使用哈希来引用打开的手风琴? 这里有一个关于使用cookie记住手风琴早期状态的相关项目:***.com/questions/1458724/… 更新:这个问题是针对 Bootstrap 2.x.x 的,对于 Bootstrap 3.x.x,请参考我的答案。 【参考方案1】:

您可以通过 cookie 轻松解决此问题。有很多简化的库,比如我在下面的示例中使用的https://github.com/carhartl/jquery-cookie:

<script src="https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js"></script>

将以下代码添加到脚本部分(#accordion2 指的是修改后的 twitter 引导示例,我在后面列出)

$(document).ready(function() 
    var last=$.cookie('activeAccordionGroup');
    if (last!=null) 
        //remove default collapse settings
        $("#accordion2 .collapse").removeClass('in');
        //show the last visible group
        $("#"+last).collapse("show");
    
);

//when a group is shown, save it as the active accordion group
$("#accordion2").bind('shown', function() 
    var active=$("#accordion2 .in").attr('id');
    $.cookie('activeAccordionGroup', active)
);

你就完成了!这里是 http://twitter.github.com/bootstrap/javascript.html#collapse 示例的修改版本,带有可点击的链接,当您返回时 - 最后显示的手风琴组会自动打开

<div class="accordion" id="accordion2">
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne">
        Collapsible Group Item #1
      </a>
    </div>
    <div id="collapseOne" class="accordion-body collapse in">
      <div class="accordion-inner">
        Link : <a href="http://google.com">google.com</a>
      </div>
    </div>
  </div>
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
        Collapsible Group Item #2
      </a>
    </div>
    <div id="collapseTwo" class="accordion-body collapse">
      <div class="accordion-inner">
        Link : <a href="http://***.com">***.com</a>
      </div>
    </div>
  </div>
  <div class="accordion-group">
    <div class="accordion-heading">
      <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseThree">
        Collapsible Group Item #3
      </a>
    </div>
    <div id="collapseThree" class="accordion-body collapse">
      <div class="accordion-inner">
        Link : <a href="http://cryptozoologynews.blogspot.com/">cryptozoology news</a>
      </div>
    </div>
  </div>
</div>

【讨论】:

谢谢,我还没有尝试过,但是根据您的解释和朋友的相同建议,我认为这是要走的路。 物品必须有id,我忘了说 Bootstrap 3 将事件名称更新为shown.bs.collapse(如下面答案所示) @MatsLindh,你是对的 - 这是一个 BS 2.x 问题,两年后用 bootstrap-3 和特定的 3.x 答案标记。【参考方案2】:

Bootstrap 3.x.x 中,您必须使用以下脚本将上次打开状态保存在 cookie 中。

HTML 标记

<div class="panel-group" id="accordion">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne">Collapsible Group
                    Item #1 </a>
            </h4>
        </div>
        <div id="collapseOne" class="panel-collapse collapse in">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
                ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
                truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
                a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
                keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
                Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
                labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseTwo">Collapsible Group
                    Item #2 </a>
            </h4>
        </div>
        <div id="collapseTwo" class="panel-collapse collapse">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
                ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
                truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
                a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
                keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
                Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
                labore sustainable VHS.
            </div>
        </div>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h4 class="panel-title">
                <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree">Collapsible
                    Group Item #3 </a>
            </h4>
        </div>
        <div id="collapseThree" class="panel-collapse collapse">
            <div class="panel-body">
                Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson
                ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food
                truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put
                a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim
                keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
                Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table,
                raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus
                labore sustainable VHS.
            </div>
        </div>
    </div>
</div>

jQuery

  $(document).ready(function () 
        //when a group is shown, save it as the active accordion group
        $("#accordion").on('shown.bs.collapse', function () 
            var active = $("#accordion .in").attr('id');
            $.cookie('activeAccordionGroup', active);
          //  alert(active);
        );
        $("#accordion").on('hidden.bs.collapse', function () 
            $.removeCookie('activeAccordionGroup');
        );
        var last = $.cookie('activeAccordionGroup');
        if (last != null) 
            //remove default collapse settings
            $("#accordion .panel-collapse").removeClass('in');
            //show the account_last visible group
            $("#" + last).addClass("in");
        
    );

【讨论】:

这是一个很好的答案,对我帮助很大,但我认为您需要指出,您必须为 jquery 下载一个特殊的附加组件才能使 cookie 部分正常工作。我看到选定的答案提到了这一点,但是当我看到您的答案与 Bootstrap 3.x 直接相关时,我有点眼熟 或者只使用 localStorage 而不是 $.cookie。 您是否遇到过第一个手风琴在进入内部页面时无法保持打开的问题? 要更新 Bootstrap 4 的这个答案,将对“.in”类的引用替换为“.show”类。包括将 .removeClass 和 .addClass 更改为 ("show")。【参考方案3】:

我尝试了上面建议的技术,它对我有用(有点),但在某些情况下调用 .collapse("show") 似乎会破坏手风琴切换行为。打开第一个面板将使先前打开的面板保持打开状态。我通过添加类“in”来解决这个问题:

$(document).ready(function() 
    var last=$.cookie('activeAccordionGroup');
    if (last!=null) 
        //remove default collapse settings
        $("#accordion .panel-collapse").removeClass('in');
        //show the account_last visible group
        $("#" + last).addClass("in");
    
);

否则,感谢 davidkonrad 让我走上正轨。

【讨论】:

【参考方案4】:

谢谢你,它有效。我对其进行了一些修改,以简单地保留特定 DIV 的显示/隐藏状态(而不是特定于在 DIV 列表中仅显示一个 DIV)。

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

<script language="javascript" type="text/javascript">
    function retainDivCollapsedState(nameOfDiv, nameOfHeader) 
        // when the div is shown, save a cookie with a value of 'true'
        $("#" + nameOfDiv).on('shown.bs.collapse', function () 
            $.cookie(nameOfDiv, "true"); // this is a cookie.  named the same as the control (poor practice) for brevity 
        );
        // when the div is collapsed, remove the same cookie
        $("#" + nameOfDiv).on('hidden.bs.collapse', function () 
            $.removeCookie(nameOfDiv);
        );

        // on page load, show or hide the div (and stylized the header) according to the cookie (if it exists)
        var showDiv = $.cookie(nameOfDiv);
        if (showDiv != null) 
            $("#" + nameOfDiv).addClass("in");                      // The div to show
            $("#" + nameOfHeader).removeClass("collapsed");         // The header to stylize as expanded
        
    ;
</script>

<script language="javascript" type="text/javascript">
    $(document).ready(
        retainDivCollapsedState("divName", "divHeaderName")
    );
</script>

【讨论】:

认为您可以发布一个 jsfiddle 页面或类似内容?我认为你的做我想做的,但我错过了一些东西。【参考方案5】:

另一个可用的选项是使用 url 哈希。

$(document).ready(function () 
    var hash = window.location.hash;
    if (hash) 
        $("#accordion .panel-collapse").removeClass('in');
        $(hash).addClass('in');
    

    $('#accordion').on('shown.bs.collapse', function () 
        var activeId = $("#accordion .in").attr('id');
        window.location.hash = activeId;
    );

    $('#accordion').on('hidden.bs.collapse', function () 
        window.location.hash = '';
    );
);

【讨论】:

【参考方案6】:

更新答案

好的,伙计们,所以我投入了一些时间来让它发挥作用。主要是因为我发现的所有答案都超级旧且没有更新。

这将适用于:

引导 3.x.x 引导程序 4.x.x 引导 5.x.x

注意: cookie 更新到新的 Github 存储库 https://github.com/js-cookie/js-cookie 的用法已更改,例如,现在 $.cookie('name'); 改为 Cookies.get('name');

包括

<script src="https://cdn.jsdelivr.net/npm/js-cookie@rc/dist/js.cookie.min.js"></script>    

脚本

$(document).ready(function() 

      var last=Cookies.get('activeAccordionGroup');

      if (last!=null) 
          //remove default collapse settings
          $("#accordion .collapse").removeClass('show');
          //show the last visible group
          $("#"+last).collapse("show");
      
 );

 //when a group is shown, save it as the active accordion group
 $("#accordion").bind('shown.bs.collapse', function() 
      var active=$("#accordion .show").attr('id');
      Cookies.set('activeAccordionGroup', active);
  );

变化:

引导事件不再是shown,而是shown.bs.collapse Cookie 使用情况

手风琴 HTML

<div id="accordion">
  <div class="card">
    <div class="card-header" id="headingOne">
      <h5 class="mb-0">
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
          Collapsible Group Item #1
        </button>
      </h5>
    </div>

    <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingTwo">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          Collapsible Group Item #2
        </button>
      </h5>
    </div>
    <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="card">
    <div class="card-header" id="headingThree">
      <h5 class="mb-0">
        <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          Collapsible Group Item #3
        </button>
      </h5>
    </div>
    <div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordion">
      <div class="card-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>

【讨论】:

请注意这里的任何人,您的一些 html 没有更新到最新版本的 Bootstrap。例如,它将是 data-bs-toggle 而不是 data-toggle【参考方案7】:

谢谢你,发现它很有帮助,但如果你使用的是 Bootstrap 3 和最新的 jquery,这可以工作:

$("#accordion").on('shown.bs.collapse', function()

   ...
);

希望这可以节省其他人一些时间....

【讨论】:

以上是关于在页面刷新/导航时保留 Twitter Bootstrap 折叠状态的主要内容,如果未能解决你的问题,请参考以下文章

将页脚刷新到页面底部,twitter bootstrap

页面刷新时如何记住或保留当前标签?

如何在页面刷新时保留 Chrome DOM 断点?

javascript中的Websockets,页面刷新或导航到其他页面时连接终止[重复]

角度刷新后将数据保留在页面中

Android 组件导航如何防止地图页面在每次点击时刷新