单击BROWSER后退按钮关闭模态

时间:2017-03-22 20:00:14

标签: javascript modal-dialog

目前我只有这个:

```

<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中,以便人们可以在浏览器中单击后退按钮返回。

我有X关闭按钮,除了很多人使用后退按钮返回的所有内容,我想添加它。

有没有一种简单的方法来实现这个目标?

2 个答案:

答案 0 :(得分: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
}

使用上面的function设置您需要的网址,并在拨打按钮时执行此操作

window.location.href = ensureHash("#foo=bar");

答案 1 :(得分:0)

正在寻找纯粹的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");
};