簡體   English   中英

我的 javascript function 工作不正常

[英]My javascript function is not working properly

我正在做一個網站項目。
我在 w3schools 中看到了用於圖像的 animation。
我已經試過了,它只適用於一張照片——

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal
var img = document.getElementById('a');
var modalImg = document.getElementById("img01");


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

但我想將它用於多個圖像。
所以我創建了一個 function 像這樣:

function myBeautifulFunc(imageId, modalImageId) {

  var modal = document.getElementById('myModal');

  var img = document.getElementById(imageId);
  var modalImg = document.getElementById(modalImageId);
  

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

並稱之為 function:
myBeautifulFunc('a', 'img01')

結果是:
它適用於第一張圖片,但是當我在第二張嘗試時,
它看起來像這樣: https://ibb.co/Mk8Xw1Z

當我點擊它時,我只想顯示一張圖片,
但它顯示了兩個圖像。

我怎么解決這個問題?

您關閉的 function span.onclick = function()沒有隱藏子項,因此第二次單擊時,您會看到上次單擊時的上一個圖像和 modalImage 。

function myBeautifulFunc(imageId, modalImageId) {

  var modal = document.getElementById('myModal');

  var img = document.getElementById(imageId);
  var modalImg = document.getElementById(modalImageId);
  

  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";
    img.style.display = "none"         // hide this also
    modalImg.style.display = "none"     // hide this also
  }
}

在任何點擊之前

  • .myModal = 隱藏
  • img1 = 隱藏
  • modalImg1 = 隱藏

第一次點擊后關閉

  • .myModal = 隱藏
  • img1 = 可見
  • modalImg1 = 可見

第二次點擊后

  • .myModal = 隱藏
  • img1 = 可見
  • modalImg1 = 可見
  • img2 = 可見
  • modalImg2 = 可見

暫無
暫無

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

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