【问题标题】:dynamically displaying images for Lightbox image ejs为 Lightbox 图像 ejs 动态显示图像
【发布时间】:2021-01-20 08:46:23
【问题描述】:

我正在尝试将图像动态加载到我必须工作的表格中,但我试图让它工作,如果我单击图像,会弹出一个灯箱,使其显示图像大。我无法让它工作。

ejs:

<td>
<input id="<%= data[i].IMAGE %>" type="button" src="<%= data[i].IMAGE %>" alt="ORIGINAL PRODUCT IMAGE" value="See Current Image" width="300" height="200">
</td>

js:

// 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("img01");
                var captionText = document.getElementById("caption");
                img.onclick = function(){
                    modal.style.display = "block";
                    modalImg.src = this.src;
                    modalImg.alt = this.alt;
                    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";
                }

它只适用于我表中的第一张图片,不知道如何修复。谢谢

【问题讨论】:

    标签: javascript html node.js ejs


    【解决方案1】:

    您通过 id 获取 img,您应该遍历 DOM 中的所有 img,并为每个 img 添加事件。

    不能这样: 使用id = myImg 向元素添加类,在本例中为class="myImgLightBox"

    // 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 imgs = document.getElementsByClassName('myImgLightBox');
                    var modalImg = document.getElementById("img01");
                    var captionText = document.getElementById("caption");
                    for(let img of imgs){
                     img.onclick = function(){
                         modal.style.display = "block";
                         modalImg.src = this.src;
                         modalImg.alt = this.alt;
                         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";
                    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多