javascript - 在模态弹出窗口内插入图像

标签 javascript

我正在制作一个带有模型弹出窗口的图像库,JavaScript 代码可以正常工作,但仅适用于图库弹出模式框的第一张图像。我如何使用每个图像弹出模式? 非常感谢任何帮助,谢谢。

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</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 myImgvar 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/

相关文章:

javascript - 使用mysql数据库在d3中绘制条形图

javascript - HTM5本地存储: Save a game process for every logged in player

javascript - 禁用表中的按钮

javascript - jQuery/javascript 不适用于所有页面

javascript - 用于隐藏基于 HTML5 数据标签的元素的 jQuery 函数未在 Click 上运行

javascript - 链接到新页面并在新打开页面的指定滚动点停止

javascript - 动画(淡入)img src 如果加载 react #noJQuery

javascript - 如何将搜索框链接到我页面上的网站?

javascript - 图片不可见(无法识别来源)

javascript - Ext.list.Tree 存储和模板