通过点击浏览器返回按钮关闭模态框

3
目前我只有这个:

```

<div data-slideid="1" class="slide">
            <div class="row">
              <div class="col-md-12 text-center modal-intro">
                <div class="container"><img src="assets/images/work/logo1.png" width="100" height="100" alt="Logo" class="img-circle"/><span>ABOUT</span>
                  <h3>Some text</h3>
                  <p>some more text </p>
                </div>
              </div>
            </div>

基本上,当单击按钮时,它只会在同一URL上滑动模态。当模态打开时,我需要添加#或其他内容到URL中,以便人们可以单击浏览器的后退按钮返回。

我有关闭按钮和其他所有内容,但是很多人使用后退按钮返回,我希望添加此功能。是否有一种简单的方法来实现这个目标?


jQuery 历史插件 - mplungjan
好的,我会检查一下。谢谢你,再见。 - The Garrus
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate - Daniel Lizik
html5History api - ArtemSky
2个回答

1

我在寻找纯JS技巧来使其工作,并想出了这个解决方案:

events() {
  // listen for close icon click
  this.closeIcon.addEventListener("click", () => this.closeModal());

  // listen for keyboard
  document.addEventListener("keyup", (e) => this.keyboardClose(e));

  // when the user clicks back in the browser, close modal window
  // basically works on any state change, on forward too, but it doesn't really matters in my case
  window.onpopstate = function () {
    document.querySelector(".modal").classList.remove("modal--visible");
  };
}

//adds ?modal to the link and creates new state in the browser history
openModal(e) {
  this.modal.classList.add("modal--visible");
  history.pushState({ modal: 1 }, "modal", "?modal");
}

//if modal is closed in any way, move back in history (without reloading the page)
closeModal() {
  this.modal.classList.remove("modal--visible");
  history.back();
}

//if esc or backspace is pressed, close the modal
keyboardClose(e) {
  if (e.keyCode == 27 || e.keyCode == 8) {
    this.closeModal();
}

//if modal is closed in any way, move back in history (without reloading the page)
window.onpopstate = function () {
  document.querySelector(".modal").classList.remove("modal--visible");
};

1
function ensureHash(newHash) {
    if (window.location.hash) {
        return window.location.href.substring(0, window.location.href.lastIndexOf(window.location.hash)) + newHash;
    }
    return window.location.hash + newHash
}

使用上面的函数来设置所需的URL,并在调用按钮时执行此操作。
window.location.href = ensureHash("#foo=bar");

好的Lajos,我有这个<a href="#work-gallery" data-slideID="0" class="open-gallery-link"> 如果我执行 $(".open-gallery-link").on('click', function(){ window.location.href = ensureHash("#foo=bar"); });它不起作用,我做错了什么?我也复制/粘贴了上面的函数。 - The Garrus
@TheGarrus,为什么在你的情况下它不起作用?控制台中是否有错误消息?还是有不良行为?有一件事是确定的:您的锚标记中有一个指向哈希的href。如果您没有为其定义任何Javascript,则单击它将使页面跳转到具有哈希后面的值作为id的标记。如果编写一些影响单击的Javascript,则需要在其末尾添加return false;以防止默认浏览器事件。 - Lajos Arpad
如果我按返回按钮,它只会删除哈希值。它并没有真正返回到上一页。 - The Garrus
1
我已经让它工作了,很酷。我还有e.preventDefault,这可能是原因。 - The Garrus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接