Bootstrap 3.x:如何在单击模态触发器时更改 url? [英] Bootstrap 3.x: how to have url change upon clicking modal trigger?
问题描述
使用Bootstrap v3.3.5
我有一个使用 url domain.com/companies
I have a webpage that is using the url domain.com/companies
这是我对该网页中的模态的触发器.
This is my trigger for the modal in that webpage.
<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>
这将成功触发此模态
<div id="modal-add-company" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
但是,网址不会更改为 domain.com/companies#modal-add-company
However, the url does not change to domain.com/companies#modal-add-company
url domain.com/companies#modal-add-company
实际上也不会在重新加载时触发模态.
Nor does the url domain.com/companies#modal-add-company
actually trigger the modal on reload.
我需要做什么才能拥有以下内容:
What do I need to do to have the following:
- 每当我触发模态并显示模态时,将 url 更改为
domain.com/companies#modal-add-company
,并且 - 如果我直接输入网址
domain.com/companies#modal-add-company
,则会显示模态
- change the url to
domain.com/companies#modal-add-company
whenever I trigger the modal and the modal is shown, and - if i directly type the url
domain.com/companies#modal-add-company
, the modal is shown
推荐答案
使用 jQuery 这可能是一个可行的解决方案
Using jQuery this could be a viable solution
$(document).ready(function(){
$(window.location.hash).modal('show');
$('a[data-toggle="modal"]').click(function(){
window.location.hash = $(this).attr('href');
});
});
假设您有一个触发器可以像这样关闭模态:
Assuming you have a trigger to close the modal like this:
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
您可以在上面的代码块下方添加:
You can add this below the code block above:
$('button[data-dismiss="modal"]').click(function(){
var original = window.location.href.substr(0, window.location.href.indexOf('#'))
history.replaceState({}, document.title, original);
});
并且假设您希望转义按钮仍然能够关闭模态,并更改 url 整个代码块将如下所示:
And assuming you want escape button to still be able to close the modal, and also change the url the whole code block would look like this:
$(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();
});
感谢 https://stackoverflow.com/a/13201843/80353 关于如何使用模态关闭事件.
Credit to https://stackoverflow.com/a/13201843/80353 about how to use modal close event.
这篇关于Bootstrap 3.x:如何在单击模态触发器时更改 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!