如何通过URL打开位于模态上的特定 Bootstrap 选项卡?

eulz3vhy  于 2022-12-08  发布在  Bootstrap
关注(0)|答案(2)|浏览(173)

我想通过URL打开一个特定的选项卡。为了打开模态,我在网站的末尾添加了以下JavaScript。通过输入website.com/#modal-6,它将打开激活了模态6的网站。

document.addEventListener("DOMContentLoaded", function() {
    if (window.location.href.indexOf("#modal-6") > -1) {
        var myModal = new bootstrap.Modal(document.getElementById('modal-6'));
        myModal.show();
    }
});

此模态包含多个选项卡。如何才能实现在通过www.example.com加载网站时显示id=tab-13的选项卡website.com/#modal-6?
HTML代码如下所示:

<ul id="tabContainer-11" class="nav nav-tabs tabcontainer mb-3" role="tablist">
    <li class="nav-item" role="presentation">
        <button id="tab-12" class="nav-link" data-bs-target="#tab-content-12" data-bs-toggle="tab" role="tab" aria-controls="tab-content-12" aria-selected="false"> Login </button>
    </li>
    <li class="nav-item" role="presentation">
        <button id="tab-13" class="nav-link active" data-bs-target="#tab-content-13" data-bs-toggle="tab" role="tab" aria-controls="tab-content-13" aria-selected="true"> ...or subscribe now! </button>
    </li>
</ul>
pcrecxhr

pcrecxhr1#

您可以利用模态事件shown.bs.modal来调用该函数,以使用tab.show()显示选项卡。

odopli94

odopli942#

太棒了!谢谢你告诉我!
所以代码是:

// show modal with id=modal-6, if url contains "#modal-6"
 document.addEventListener("DOMContentLoaded", function() {

   if (window.location.href.indexOf("#modal-6") > -1) {

     var myModal = new bootstrap.Modal(document.getElementById('modal-6'));
     //var myTab = new bootstrap.Tab(document.getElementById('tab-13'));
     myModal.show();

     //open tab with id=tab-13, when modal is shown
     var myModalEl = document.getElementById('modal-6')
     myModalEl.addEventListener('shown.bs.modal', function(event) {
       // do something...
       var myTab = document.querySelector('#tab-13');
       var tab = new bootstrap.Tab(myTab);

       tab.show();
     });

   }

 });

相关问题