Bootstrap 3.x:点击模态触发器后如何更改网址?

Kim*_*cks 6 twitter-bootstrap bootstrap-modal twitter-bootstrap-3

使用Bootstrap v3.3.5

我有一个使用网址的网页 domain.com/companies

这是我在该网页中模式的触发器.

<a href="#modal-add-company" class="btn btn-effect-ripple btn-effect-ripple btn-success" data-toggle="modal"><i class="fa fa-plus"></i> New Company</a>
Run Code Online (Sandbox Code Playgroud)

这将成功触发此模态

<div id="modal-add-company" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
Run Code Online (Sandbox Code Playgroud)

但是,网址不会更改为 domain.com/companies#modal-add-company

url domain.com/companies#modal-add-company实际上也不会在重新加载时触发模态.

如何进行以下操作我需要做什么:

  1. domain.com/companies#modal-add-company每次触发模态时都会更改网址,并显示模态,并且
  2. 如果我直接输入网址domain.com/companies#modal-add-company,则显示模态

Jon*_*ega 17

使用jQuery这可能是一个可行的解决方案

$(document).ready(function(){
   $(window.location.hash).modal('show');
   $('a[data-toggle="modal"]').click(function(){
      window.location.hash = $(this).attr('href');
   });
});
Run Code Online (Sandbox Code Playgroud)

假设您有一个触发器来关闭模态,如下所示:

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
Run Code Online (Sandbox Code Playgroud)

您可以在上面的代码块下面添加:

$('button[data-dismiss="modal"]').click(function(){
     var original = window.location.href.substr(0, window.location.href.indexOf('#'))
     history.replaceState({}, document.title, original);
 });
Run Code Online (Sandbox Code Playgroud)

并且假设您希望转义按钮仍然能够关闭模态,并且还更改URL,整个代码块将如下所示:

    $(window.location.hash).modal('show');
    $('a[data-toggle="modal"]').click(function(){
        window.location.hash = $(this).attr('href');
    });

    function revertToOriginalURL() {
        var original = window.location.href.substr(0, window.location.href.indexOf('#'))
        history.replaceState({}, document.title, original);
    }

    $('.modal').on('hidden.bs.modal', function () {
        revertToOriginalURL();
    });
Run Code Online (Sandbox Code Playgroud)

感谢/sf/answers/924129041/关于如何使用模态关闭事件.