猿问

我的 javascript 函数无法正常工作

我正在做一个网站项目。

我在 w3schools 中看到了图像动画。

我已经试过了,它只适用于一张照片——


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


当我点击它时,我只想显示一张图片,

但它显示了两张图片。


我怎么解决这个问题?


慕桂英3389331
浏览 112回答 1
1回答

守候你守候我

您的关闭功能span.onclick = function()不会隐藏子项,因此第二次单击时,您会看到上次单击时的上一个图像和 modalImage。function myBeautifulFunc(imageId, modalImageId) {&nbsp; var modal = document.getElementById('myModal');&nbsp; var img = document.getElementById(imageId);&nbsp; var modalImg = document.getElementById(modalImageId);&nbsp;&nbsp;&nbsp; img.onclick = function() {&nbsp; &nbsp; modal.style.display = "block";&nbsp; &nbsp; modalImg.src = this.src;&nbsp; }&nbsp; // Get the <span> element that closes the modal&nbsp; var span = document.getElementsByClassName("close")[0];&nbsp; // When the user clicks on <span> (x), close the modal&nbsp; span.onclick = function() {&nbsp; &nbsp; modal.style.display = "none";&nbsp; &nbsp; img.style.display = "none"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// hide this also&nbsp; &nbsp; modalImg.style.display = "none"&nbsp; &nbsp; &nbsp;// hide this also&nbsp; }}在任何点击之前.myModal = 隐藏img1 = 隐藏modalImg1 = 隐藏第一次点击后关闭.myModal = 隐藏img1 = 可见modalImg1 = 可见第二次点击后.myModal = 隐藏img1 = 可见modalImg1 = 可见img2 = 可见modalImg2 = 可见
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答