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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12733238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:07:58  来源:igfitidea点击:

Retain Twitter Bootstrap Collapse state on Page refresh/Navigation

javascriptjquerytwitter-bootstraptwitter-bootstrap-3

提问by gnudle

I'm using Bootstrap "collapse" plugin to make an accordion for a long list of links. The accordion-body tag includes "collapse" so all the groups are collapsed when the page loads. When you open a group and click on a link, it takes you to a new page to see some detail and then you click a back link or the browser back to return to the list. Unfortunately, when you return the accordion is back in its collapsed state and you have to open the group again and find where you were. I anticipate a lot of this back and forth navigation and this behavior is going to be frustrating.

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

Is there some way to preserve the user's place and go back to it, or just prevent the page from reloading or the javascript from firing again.

有没有办法保留用户的位置并返回到它,或者只是防止页面重新加载或 javascript 再次触发。

I thought the solution might be along these lines, but not sure. Twitter bootstrap: adding a class to the open accordion title

我认为解决方案可能是这样的,但不确定。 Twitter 引导程序:向打开的手风琴标题添加一个类

采纳答案by davidkonrad

You can very easily solve this by a cookie. There is a lot of simplified libraries, like https://github.com/carhartl/jquery-cookieas I use in the example below :

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

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

add the following code to a script section (#accordion2refers to the modfied twitter bootstrap example, I list afterwards)

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

$(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)
});

And you are done! Here a modified version of the example at http://twitter.github.com/bootstrap/javascript.html#collapsewith clickable links, when you go back - the last shown accordion group opens up automatically

你已经完成了!这是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://stackoverflow.com">stackoverflow.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>

回答by Ravimallya

In Bootstrap 3.x.xyou have to use the following script to save the last open state in cookies.

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

HTML Markup

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");
        }
    });

回答by Devindra

I tried the technique suggested above and it worked for me (sort of) but calling .collapse("show") seemed to break the accordion toggle behavior in some instances. Opening first panel would leave previously opened panel in open state. I got round this with jQuery by adding class "in" instead:

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

$(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");
    }
});

Otherwise, thanks davidkonrad putting me on right track.

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

回答by dankeshawn

Thanks for this, it works. I modified it a bit to simply retain the show/hide state of a specific DIV (and not specific to showing only one DIV in a list of DIVs).

谢谢你,它有效。我稍微修改了它以简单地保留特定 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>

回答by kheit

Another option available is to use the url hash.

另一个可用的选项是使用 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 = '';
    });
});

回答by ws8

Thanks for this, found it very helpful, but if you are using Bootstrap 3 & latest jquery, this works:

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

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

Hope this saves others some time....

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