为了账号安全,请及时绑定邮箱和手机立即绑定

我的 javascript 函数无法正常工作

我的 javascript 函数无法正常工作

慕桂英3389331 2022-11-03 10:12:26
我正在做一个网站项目。我在 w3schools 中看到了图像动画。我已经试过了,它只适用于一张照片——// Get the modalvar modal = document.getElementById('myModal');// Get the image and insert it inside the modalvar 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 modalvar span = document.getElementsByClassName("close")[0];// When the user clicks on <span> (x), close the modalspan.onclick = function() {  modal.style.display = "none";}但我想将它用于多个图像。所以我创建了一个这样的函数: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";  }}并调用了这个函数:myBeautifulFunc('a', 'img01')结果是:它适用于第一张图片,但是当我在第二张尝试时,它看起来像这样:https ://ibb.co/Mk8Xw1Z当我点击它时,我只想显示一张图片,但它显示了两张图片。我怎么解决这个问题?
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

您的关闭功能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 = 可见


查看完整回答
反对 回复 2022-11-03
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信