簡體   English   中英

如何為多個圖像打開模態圖像

[英]How to open a modal image for multiple images

在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()並取消注釋了先前代碼的某些部分。 但是現在即使對於一張圖像它也不起作用,它打開了沒有圖像的模態。

謝謝您的幫助

控制台中的錯誤是Uncaught ReferenceError: openModal is not defined 這意味着該函數在未定義的范圍內運行。 一個簡單的解決方法是在全局范圍內定義它,例如window:

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

但是,您不應再使用不使用onclick了(w3schools現在有點老了),就像這個答案說的那樣

您要做的是將事件偵聽器附加到圖像。 循環瀏覽所有圖像,並使用addEventListener('click' ...)偵聽單擊時的聲音。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM