我正在制作一个带有模型弹出窗口的图像库,JavaScript 代码可以正常工作,但仅适用于图库弹出模式框的第一张图像。我如何使用每个图像弹出模式? 非常感谢任何帮助,谢谢。
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="myImg1">
<div id="caption"></div>
</div>
<?php echo '<img id="myImg" src="'.esc_url( $info['0'] ).'" alt="Snow" style="width:100%;max-width:300px">'; ?>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("myImg1");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
}
// 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>
最佳答案
问题可能是您的所有图像都具有相同的 ID myImg。
var img = document.getElementById('myImg');
始终选择具有给定 id 的第一个元素。你可以尝试将js放在一个函数中并调用它onclick。
function imgPopup(){
var modal = document.getElementById('myModal');
var modalImg = document.getElementById("myImg1");
modal.style.display = "block";
modalImg.src = this.src;
}
<?php echo '<img id="myImg" src="'.esc_url( $info['0'] ).'" onclick="imgPopup();" alt="Snow" style="width:100%;max-width:300px">'; ?>
关于javascript - 在模态弹出窗口内插入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53280096/