我想使用选择器来选择页面上的每个图像以放入模态,而无需重写每个图像的整个脚本。 我觉得这是一个愚蠢的问题,但我一直在尝试不同的事情。 现在我正在使用var img = document.getElementById("article01"(;选择一个图像,因为这就是你可以用getElementById做的全部事情。因此,我想选择列出的两个图像,这样我就不会为每个图像重写整个脚本,因为页面上会有更多图像。我尝试使用 getelementbyclass 和标签名称,但我想我卡住了。
.HTML:
<!-- Trigger the Modal -->
<img id="article01" src="/images/article1.PNG" alt="" style="width:100%;max-width:300px">
<img id="article01-2" src="/images/article1-2.PNG" alt="" style="width:100%;max-width:300px">
<!-- The Modal -->
<div id="modal1" class="modal">
<!-- The Close Button -->
<span class="close">×</span>
<!-- Modal Content (The Image) -->
<img class="modal-content" id="img01">
<!-- Modal Caption (Image Text) -->
<div id="caption"></div>
</div>
Javascript:
<script>
// Get the modal
var modal = document.getElementById("modal1");
*var img = document.getElementById("article01");*
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
document.querySelectorAll()
来获取所有图像的nodeList。 例如,如果您创建了这样的图像列表:
<img class="selectable" src="article-1" />
<img class="selectable" src="article-2" />
<img class="selectable" src="article-2" />
您可以使用 ...
document.querySelectorAll('img.selectable')
.forEach((img) => {
img.addEventListener('click', (e) => showModal(e.target)); //or use img.onclick = ...
});
这是一个代码笔的链接,展示了如何做到这一点的演示......
这是我从你的帖子中得到的。我认为您正在寻找的是document.querySelector((
<!-- Trigger the Modal -->
<img alt="this is a caption" src="https://livebrooks.com/wp-content/uploads/2017/07/fpo.gif" style="width:100%;max-width:300px">
<img alt="this is the second caption" src="https://livebrooks.com/wp-content/uploads/2017/07/fpo.gif" style="width:100%;max-width:300px">
<!-- The Modal -->
<div id="modalWrap" class="modal">
<!-- The Close Button -->
<span class="close" onclick="document.querySelector('#modalWrap').remove()">×</span>
</div>
for (var i of document.querySelectorAll("img")) {
makeModal(i.src, i.getAttribute("alt"));
}
function makeModal(src, caption) {
//modal wrap
var modalWrap = document.querySelector("#modalWrap");
//img
var imgElement = document.createElement("img");
imgElement.src = src;
imgElement.style.maxWidth = "300px";
//caption
var captionElement = document.createElement("p");
captionElement.innerText = caption;
//adding elements to modalWrap
modalWrap.appendChild(imgElement);
modalWrap.appendChild(captionElement);
}