bootstrap 选项卡 tab 切换功能是通过 #field
完成切换的,当选择另外一个选项卡并刷新页面后,如何让页面直接显示当前已选中的状态?这里介绍一种实现方法。
-
首先,当点击 tab 选项卡时,用 js 将当前的
#field
标识追加到地址栏$('.nav-tabs a').on('shown.bs.tab', function (e) { history.pushState(null,null, e.target.hash); // location.hash = this.getAttribute("href"); });
-
然后,当刷新页面时,获取地址栏
#field
标识,渲染 tab 选中状态var hash = window.location.hash; if (hash) { $('.nav-tabs a[href="' + hash + '"]').tab('show'); }
至此,功能完成。