2017-03-01 69 views
0

在w3schools网站上,我找到了一个对话框/弹出窗口的教程。我想用更多的图像来实现这一点。如何打开多个图像的模态图像

我的代码:

<img onclick="openModal()" src="low/dn-64.jpg" data-highres="high/dn-64.jpg" width="300" height="400"> 

<!-- Modal --> 
<div id="myModal" class="modal"> 
    <!-- Close button --> 
    <span class="close">&times;</span> 
    <!-- Modal content --> 
    <img class="modal-content" id="modal-image"> 
</div> 

<script type="text/javascript"> 
    var modal = document.getElementById('myModal'); 
    var img = document.getElementById('myImg'); 
    var modalImg = document.getElementById('modal-image'); 

    function openModal() { 
     modal.style.display = "block"; 
     modalImg.src = this.getAttribute("data-highres"); 
    } 

    /*img.onclick = function() { 
    modal.style.display = "block"; 
    modalImg.src = this.getAttribute("data-highres"); 
    }*/ 

    var span = document.getElementsByClassName("close")[0]; 

    span.onclick = function() { 
    modal.style.display = "none"; 
    } 

    window.onclick = function() { 
    if(event.target == modal) { 
     modal.style.display = "none"; 
     } 
    } 
</script> 

CSS:

#myImg { 
    cursor: zoom-in; 
    transition: 0.3s; 
    } 

    #myImg:hover { 
    opacity: 0.7; 
    } 

    .modal { 
    display: none; 
    position: fixed; 
    z-index: 1; 
    padding-top: 60px; 
    left: 0; 
    top: 0; 
    width: 100%; 
    height: 100%; 
    overflow: auto; 
    background-color: rgb(0,0,0); 
    background-color: rgba(0,0,0,0.8); 
    } 

    .modal-content { 
    margin: auto; 
    display: block; 
    width: 80%; 
    max-width: 700px; 
    } 

    .close { 
    position: absolute; 
    top: 15px; 
    right: 35px; 
    color: #f1f1f1; 
    font-size: 50px; 
    font-weight: bold; 
    transition: 0.3s; 
    } 

    .close:hover, 
    .close:focus { 
    color: #bbbbbb; 
    text-decoration: none; 
    cursor: pointer; 
    } 

代码正在为一个图像。所以我添加了一个函数openModal()并取消注释了以前代码的某些部分。但是现在,即使对于一张图像,它也不起作用,它会在没有图像的情况下打开模式。

感谢你的帮助

回答

0

在控制台中的错误是Uncaught ReferenceError: openModal is not defined。这意味着该函数在未定义的范围内运行。一个简单的办法是在全球范围内来定义它,就像窗口:

window.openModal = function(img) { 
    modal.style.display = "block"; 
    modalImg.src = img.getAttribute("data-highres"); 
} 

然后

<img onclick="openModal(this);" src="low/dn-64.jpg" data-highres="high/dn-64.jpg" width="300" height="400"> 

但是,你不应该使用NOT的onclick再使用(W3Schools的是位现在老)像this answer says

你想要做的是将一个事件监听器附加到你的图像。循环播放所有图像,并使用addEventListener('click' ...)来监听它们被点击的时间。

var images = document.querySelectorAll('img'); 
for(var i=0, len = images.length; i < len; i++){ 
    images[i].addEventListener('click', openModal); 
} 
+0

谢谢你的快速解决方案! –