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

标签 javascript html css

我在一个页面中有多个模态框,当我点击时这些模态框会打开。

但是他们不生成链接

我希望他们有他们自己的链接,例如: www.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. 不使用散列;
  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)

就是这样。当您打开 url www.yoursite.com?openmodal=myModal5 - id 为 myModal5 的模式将在页面加载后打开。

关于javascript - 直接链接到具有多个模态的开放模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55327451/

相关文章:

javascript - 停止脚本调试错误对话框出现在 ie8 中?

javascript - MySQL值不显示在图片名称中

javascript - 使用 jQuery 从 RSS 提要中提取内容

javascript - 单击图像时如何隐藏导航栏

css - 显然 1vw 不是 0.5vw+0.5vw

html - CSS Grid 中的元素填充行高?

javascript - ckeditor 错误嵌套 div 错误的解决方法?

javascript - 添加 NaN

javascript - 响应式图像 - 在不同的屏幕尺寸上调整图像大小

css - 无法让 facebook 像按钮一样坐在右边