[英]Image insert inside the modal popup
我正在使用模型彈出窗口制作一個圖像庫,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">'; ?>
請嘗試這個。 添加此行以獲取定義的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";
}
}
執行以下更新:將新圖像包裝在容器中。 將事件偵聽器添加到容器中,匹配您想要的標簽(img),然后更新模式中的src元素並顯示它:
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.