将图像插入到模式弹出窗口中

时间:2018-11-13 11:31:12

标签: 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>

3 个答案:

答案 0 :(得分:2)

问题可能是您的所有图像都具有相同的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">'; ?>

答案 1 :(得分:1)

请尝试这个。添加此行以获取定义的src

var myImg= document.getElementById("myImg");

替换您的JavaScript。

function imgPopup(){
    var modal = document.getElementById('myModal');
    var modalImg = document.getElementById("myImg1");
    var myImg= document.getElementById("myImg");

    modal.style.display = "block";
    modalImg.src = myImg.src;

    var span = document.getElementsByClassName("close")[0];
    span.onclick = function() { 
        modal.style.display = "none";
    } 
}

答案 2 :(得分:0)

执行以下更新:将新图像包装在容器中。将事件侦听器添加到容器中,匹配所需标签(img),然后更新模式中的src元素并显示它:

<!-- The Modal -->
<div id="myModal" class="modal">
  <span class="close">&times;</span>
  <img class="modal-content" id="myImg1">
  <div id="caption"></div>
</div>

<div id="gallery">
  <?php echo '<img src="'.esc_url( $info['0'] ).'" alt="Snow" style="width:100%;max-width:300px">'; ?>
</div>




<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 gallery = document.getElementById('gallery'),
    modalImg = document.getElementById("myImg1");

gallery.addEventListener('click', function(e){
    if(e.target.nodeName.toLowerCase() === 'img'){
        modalImg.src = e.target.src;
        modal.style.display = "block";
    }
});

// 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>