我在一个页面中有多个模态框,当我点击时这些模态框会打开。
但是他们不生成链接
我希望他们有他们自己的链接,例如: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";
}
}
- 不使用散列;
- 而是哈希使用搜索:
www.yourwebsite.com?openmodal=modal1
;
- 您的代码将是最简单的:
// 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
的模式将在页面加载后打开。
我是一名优秀的程序员,十分优秀!