我在一个页面中有多个模态,然后单击它们会打开这些模态。
但是他们不生成链接
我希望他们拥有自己的链接,例如: 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";
}
}
答案 0 :(得分:1)
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)
就这些了。当您打开网址www.yoursite.com?openmodal=myModal5
时-ID为myModal5
的模式将在页面加载后打开。