直接链接到具有多个模态的开放模态

时间:2019-03-24 19:06:38

标签: javascript html css

我在一个页面中有多个模态,然后单击它们会打开这些模态。

但是他们不生成链接

我希望他们拥有自己的链接,例如: wwww.mywebsite.com/test#myModal1

我尝试不成功,但互联网上至少有30个代码可用

我的每个模态都使用相同的Javascript代码,只是有些差别

例如,这是我在第五个模式中使用的代码

// Get the modal
var modal = document.getElementsByClassName('modal');

// Get the button that opens the modal
var btn = document.getElementsByClassName("myBtn");


// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close");

// When the user clicks the button, open the modal 
btn[0].onclick = function() {
    modal[0].style.display = "block";
}

btn[4].onclick = function() {
    modal[4].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
    modal[0].style.display = "none";
}

span[4].onclick = function() {
    modal[4].style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

1 个答案:

答案 0 :(得分:1)

  1. 不使用哈希;
  2. 使用搜索来代替哈希:www.yourwebsite.com?openmodal=modal1;
  3. 您的代码将是最简单的:
// modal dialog opener
const openModalDialog = (modalId) => {
  const modal = document.getElementById(modalId);
  modal.style.display = "block";
}

// callback
const openModal = () => {
  // parse search part in url "openmodal=modal1"
  const search = {}
  console.log('openModal#11111')
  window.location.search.split('&').forEach((item) => {
    const [key, value] = item.split('=')
    search[key] = value
  })
  // so, you can now find modal id from your url if its passed:
  const modalId = search.openmodal
  // and, if id is passed - do a something to open modal:
  if (modalId) {
    // your code for open modal here
    openModalDialog(modalId) 
  }
}

// add callback to document onLoad event:
window.addEventListener("DOMContentLoaded", openModal)
window.addEventListener("load", openModal)

就这些了。当您打开网址www.yoursite.com?openmodal=myModal5时-ID为myModal5的模式将在页面加载后打开。