gpt4 book ai didi

javascript - 使用几种不同的模态

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:54 25 4
gpt4 key购买 nike

我关注了this guide使用 javascript 创建美观的 CSS 模式。在我的页面上,我总共需要 8 种不同的模态。是否可以使用相同的 ID 等?我知道我必须修复 Javascript 中的一些东西,但我不知道如何做。我现在看到的唯一方法是使用唯一 ID 并复制 Javascript 并将变量更改为 ID。

但一定有更好的方法,不是吗?这样我就可以这样做:

<a id="myBtn" class="modalBtn">Button one</a>
<div id="myModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h2>Button one header</h2>
</div>
<div class="modal-body">
<p>Button one text</p>
</div>
</div>
</div>

<a id="myBtn" class="modalBtn">Button two</a>
<div id="myModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h2>Button two header</h2>
</div>
<div class="modal-body">
<p>Button two text</p>
</div>
</div>
</div>

并让它们正确显示。而不是这样做:

<a id="myBtn1" class="modalBtn">Button one</a>
<div id="myModal1" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h2>Button one header</h2>
</div>
<div class="modal-body">
<p>Button one text</p>
</div>
</div>
</div>

<a id="myBtn2" class="modalBtn">Button two</a>
<div id="myModal2" class="modal">
<div class="modal-content">
<div class="modal-header">
<span class="close">&times;</span>
<h2>Button two header</h2>
</div>
<div class="modal-body">
<p>Button two text</p>
</div>
</div>
</div>

如果我按照第二个例子去做;然后我必须复制 Javascript,使每个按钮和每个模式都有 8 个变量。必须有一种更简单、更简洁的方法来执行此操作。

有人知道我怎样才能做到这一点吗?

最佳答案

从根本上说,Id 必须是唯一的。如果你担心 javascript,你可以封装你的函数,将 id 作为参数。即-

function ModalFunction(modalId, btnId){
// Get the modal
var modal = document.getElementById(modalId);

// Get the button that opens the modal
var btn = document.getElementById(btnId);

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

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

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.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";
}
}
}

然后像这样调用它:

ModalFunction("myModal1", "myBtn1");
ModalFunction("myModal2", "myBtn2");

您可以在此处看到一个有效的 jsfiddle(带有一些附加功能)- https://jsfiddle.net/Lcmffb2b/2/

关于javascript - 使用几种不同的模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42393020/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com