繁体   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