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

9lowa7mx  于 2023-08-01  发布在  Bootstrap
关注(0)|答案(9)|浏览(150)

我正在使用Bootstrap“collapse”插件为一长串链接制作一个 accordion 。accordion-body标签包含“collapse”,因此当页面加载时,所有组都将折叠。当您打开一个组并单击一个链接时,它会将您带到一个新页面以查看一些详细信息,然后单击后退链接或浏览器返回到列表。不幸的是,当您返回时, accordion 又回到了折叠状态,您必须再次打开组并找到您所在的位置。我预计会有很多这样的来回导航,这种行为将会令人沮丧。
有没有一些方法可以保留用户的位置并返回到它,或者只是防止页面重新加载或JavaScript再次触发。
我认为解决方案可能是沿着这些路线,但不确定。Twitter bootstrap: adding a class to the open accordion title

ykejflvf

ykejflvf1#

你可以很容易地通过一个cookie来解决这个问题。有很多简化的库,比如我在下面的例子中使用的https://github.com/carhartl/jquery-cookie

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

字符串
将以下代码添加到脚本部分(#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)
});


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

<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>

xv8emn3q

xv8emn3q2#

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

cs7cruho

cs7cruho3#

我尝试了上面建议的技术,它对我有效(某种程度上),但在某些情况下,调用.collapse(“show”)似乎会破坏 accordion 切换行为。打开第一个面板将使先前打开的面板处于打开状态。我用jQuery通过添加class“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让我走上正轨。

au9on6nz

au9on6nz4#

谢谢你,它工作。我对它做了一点修改,只是简单地保留了特定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>

字符串

xxhby3vn

xxhby3vn5#

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

字符串

yx2lnoni

yx2lnoni6#

更新答案

好吧,伙计们,所以我花了一些时间试图让它工作。主要是因为我发现的所有答案都超级旧,没有更新。
这将适用于:

*Bootstrap 3.x.x
*Bootstrap 4.x.x
*Bootstrap 5.x.x
**注意:**cookie更新到新的Github存储库https://github.com/js-cookie/js-cookie,用法已更改,例如,现在是Cookies.get('name');而不是$.cookie('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);
  });

变更:

  • Bootstrap事件不再是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>

3df52oht

3df52oht7#

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

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

字符串
希望这能为其他人节省一些时间……

8fsztsew

8fsztsew8#

对于那些没有/不想使用jQuery/$的人,这是适合我的Vanilla JavaScript版本(Bootstrap版本5):

<script defer type="text/javascript">
  window.addEventListener('load',
    function () {
      document.querySelectorAll(".store-collapse").forEach(function (el) {
          el.addEventListener("shown.bs.collapse", function () {
              localStorage.setItem("coll_" + el.id, true);
              console.log('SHOW ' + el.id + "$");
          })
      });
      document.querySelectorAll(".store-collapse").forEach(function (el) {
          el.addEventListener("hidden.bs.collapse", function () {
              localStorage.setItem("coll_" + el.id, false);
              console.log('HIDE '+ el.id + "$");
          })
      });
  
      document.querySelectorAll(".store-collapse").forEach(function (el) {
          console.log('EACH ' + el.id);
          if (localStorage.getItem("coll_" + el.id) === "true") {
              console.log('INIT SHOW '+ el.id);
              el.classList.remove("collapse")
          } else if (localStorage.getItem("coll_" + el.id) === "false") {
              console.log('INIT HIDE '+ el.id);
              el.classList.add("collapse")
          }
      });
  }, false);
</script>

字符串
一些解释:

  • 我添加了store-collapse类,以便精确地选择我想要启用 * 保存/恢复折叠状态到本地存储 * 的元素。范例:
<div class="store-collapse" id="status_table"> 
      <table class="table">
      ...
    </div>
    
    <div class="store-collapse" id="info_table"> 
      <table class="table">
      ...
    </div>

  • 而不是调用一些Bootstrap JavaScript代码/instatiate对象,我选择使用Bootstrap类-它的工作没有任何问题。

参考文献:

2nbm6dog

2nbm6dog9#

如果有人仍然感兴趣,有我的Bootstrap 5.3测试代码

<script defer type="text/javascript">
    window.addEventListener('load',
        function() {
            document.querySelectorAll(".store-collapse").forEach(function(el) {
                el.addEventListener("shown.bs.collapse", function() {
                    localStorage.setItem("coll_" + el.id, true);
                    console.log('SHOW ' + el.id + "$");
                })
            });
            document.querySelectorAll(".store-collapse").forEach(function(el) {
                el.addEventListener("hidden.bs.collapse", function() {
                    localStorage.setItem("coll_" + el.id, false);
                    console.log('HIDE ' + el.id + "$");
                })
            });

            document.querySelectorAll(".store-collapse").forEach(function(el) {
                console.log('EACH ' + el.id);
                if (localStorage.getItem("coll_" + el.id) === "true") {
                    console.log('INIT SHOW ' + el.id);
                    el.classList.add("show")
                } else if (localStorage.getItem("coll_" + el.id) === "false") {
                    console.log('INIT HIDE ' + el.id);
                    el.classList.remove("show")
                }
            });
        }, false);
</script>

字符串

相关问题