元素,并添加到相应的容器中。
function addTab(tabTitle, tabContent) {
var tabList = document.getElementById(‘tabs’);
var tabContentDiv = document.getElementById(‘myTabContent’);
// 创建新的标签和内容面板
var newTab = document.createElement(‘a’);
newTab.classList.add(‘nav-item’, ‘nav-link’);
newTab.id = tabTitle.toLowerCase().replace(/\s+/g, ‘-‘);
newTab.href = ‘#’ + tabTitle.toLowerCase().replace(/\s+/g, ‘-‘);
newTab.setAttribute(‘data-toggle’, ‘tab’);
newTab.setAttribute(‘role’, ‘tab’);
newTab.setAttribute(‘aria-controls’, tabTitle.toLowerCase().replace(/\s+/g, ‘-‘));
newTab.textContent = tabTitle;
var newTabPanel = document.createElement(‘div’);
newTabPanel.classList.add(‘tab-pane’, ‘fade’);
newTabPanel.id = tabTitle.toLowerCase().replace(/\s+/g, ‘-‘);
newTabPanel.setAttribute(‘role’, ‘tabpanel’);
newTabPanel.setAttribute(‘aria-labelledby’, tabTitle.toLowerCase().replace(/\s+/g, ‘-‘));
newTabPanel.innerHTML = tabContent;
// 添加到标签页头部和内容区域
tabList.appendChild(newTab);
tabContentDiv.appendChild(newTabPanel);
}
2. 监听标签页切换
你可以使用 JavaScript 中的
tabshow
事件来监听标签页的切换。
$(‘#tabs a’).on(‘shown.bs.tab’, function (e) {
console.log(e.target.id);
});
通过以上步骤,你可以轻松地使用 Bootstrap 4 标签页组件来创建动态和交互式的页面布局。这些技巧可以帮助你构建更加丰富和用户友好的网页界面。