我使用了从 w3school 获得的模态框,我对其进行了修改以将多个模态框放在同一页面上。
我想知道是否可以让这些模式生成它们自己的链接。 示例:我打开模式 4,页面链接将更改为 mywebsite.com/modal4
我使用的代码大致是这样的
JS
// 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[1].onclick = function() {
modal[1].style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span[0].onclick = function() {
modal[0].style.display = "none";
}
span[1].onclick = function() {
modal[1].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";
}
}
HTML
<h2>Modal Example1</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn" class="myBtn">Open Modal1</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..1</p>
</div>
</div>
<h2>Modal Example2</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn" class="myBtn">Open Modal2</button>
<!-- The Modal -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal2-content">
<span class="close">×</span>
<p>Some text in the Modal..2</p>
</div>
</div>
最佳答案
您可以在打开模式时更改页面的当前 URL,如以下答案所示:Modify the URL without reloading the page .如果您转到 mywebsite.com/modal4,要加载模态,您可以编写一些 js 逻辑来获取链接,查看它是否指向模态,然后打开该模态。
您可能需要编写一些后端代码来处理这样的链接,但是,您可以尝试传递链接参数,然后使用 js 将参数从链接字符串中解析出来:How to get the value from the GET parameters?
正如 JagdeeshKumar 在下面指出的那样,您还可以导航到 website.com/htmlpage.html#modal4,您可以使用 js 获取该位置并加载模式。参见 https://www.w3schools.com/jsref/prop_loc_hash.asp
关于javascript - 带链接的模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51632788/