我从Bootstrap示例代码中获取了一个简单的模态。就像这样:
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
我希望能够通过手机上的后退按钮关闭模式,因为它占据了移动设备上的整个页面,并且在右上角搜索“x”并不是很方便。我看了一下文档,但只有一个选项可以用键盘上的Escape键关闭模态,而没有移动设备的解决方案。任何人都可以帮助我吗?
答案 0 :(得分:1)
虽然我建议使用简单的X或关闭按钮关闭模态,但您应该能够通过以下方式收听事件:
$(window).on("navigate", function (event, data) {
var direction = data.state.direction;
if (direction == 'back') {
// do something
}
if (direction == 'forward') {
// do something else
}
});
您需要收听导航事件和state.direction。
您是否考虑过将X保留在模态的静态标题中?内容可滚动..
答案 1 :(得分:1)
我通过实施https://stackoverflow.com/a/42114285/5118339和https://stackoverflow.com/a/25464754/5118339以及一些修复程序来使它工作
function handleBackPress(event) {
event.preventDefault();
event.stopPropagation();
$('.modal').modal('hide');
$('.modal-backdrop').remove();
}
var closedModalHashStateId = "#modalClosed";
var openModalHashStateId = "#modalOpen";
/* Updating the hash state creates a new entry
* in the web browser's history. The latest entry in the web browser's
* history is "modal.html#modalClosed". */
window.location.hash = closedModalHashStateId;
$(window).on('popstate', this.handleBackPress);
document.addEventListener("backbutton", this.handleBackPress, false);
/* The latest entry in the web browser's history is now "modal.html#modalOpen".
* The entry before this is "modal.html#modalClosed". */
$('.modal').on('show.bs.modal', function(e) {
window.history.pushState('forward', null, './'+openModalHashStateId);
});
/* When the user closes the modal using the Twitter Bootstrap UI,
* we just return to the previous entry in the web
* browser's history, which is "modal.html#modalClosed". This is the same thing
* that happens when the user clicks the web browser's back button. */
$('.modal').on('hide.bs.modal', function(e) {
window.history.back();
});