如何像以前的引导方法一样直接链接到引导程序 5 选项卡?:
Twitter Bootstrap 选项卡:转到页面重新加载或超链接上的特定选项卡
我尝试过以下方法:
var hash = location.hash.replace(/^#/, ""); // ^ means starting, meaning only match the first hash
if (hash) {
var someTabTriggerEl = document.querySelector("#" + hash + "");
var tab = new bootstrap.Tab(someTabTriggerEl);
tab.show();
}
假设选项卡触发器来自
<ul>
列表,并且查询字符串哈希是 href
中的目标,则在页面加载时显示选项卡的 Bootstrap 5 方法为:
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link" data-bs-toggle="tab" href="#someTarget">Some Target</a>
</li>
</ul>
document.addEventListener("DOMContentLoaded", () => {
const trigger = document.querySelector(`ul.nav a[href="${window.location.hash}"]`)
const tab = new bootstrap.Tab(trigger)
tab.show()
})
上面不会检查无效的查询字符串哈希名称或有效的 dom 元素;根据需要添加。
目前解决这个问题的方法是:
var hash = location.hash.replace(/^#/, "");
if (hash) {
var triggerEl = document.querySelector("#" + hash + "-tab");
triggerEl.click();
}
Jquery 解决方案:
$(function () {
//---if hash is provided for tab, then open and focus that tab
if (window.location.hash) {
const tab_id = window.location.hash;
const $tab = $(tab_id);
if ($tab.length) {
$tab.tab('show');
$tab[0].scrollIntoView({ behaviour: 'smooth' });
}
}
});