当我单击图片时,该图片会以弹出窗口的形式打开,但我想给我看另一张图片而不是同一张图片

时间:2018-09-03 07:34:43

标签: javascript popup

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

// Get the image and insert it inside the modal - use its "alt" text as a  caption
    var img = document.getElementById('myImg');
    var modalImg = document.getElementById("img01");
    var captionText = document.getElementById("caption");
    img.onclick = function(){
      modal.style.display = "block";
      modalImg.src =this.src;
      captionText.innerHTML = this.alt;
    }

像这样:

1 个答案:

答案 0 :(得分:1)

向图像标签添加数据属性

<img id="myImg" data-src="bigimage.png" src="smallimage.png" alt="This is the caption" />

并更改如下代码:

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

// Get the image and insert it inside the modal - use its "alt" text as a  caption
var img = document.getElementById('myImg');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function() {
  modal.style.display = "block";
  // modalImg.src = this.src;
  modalImg.src = this.getAttribute("data-src");
  captionText.innerHTML = this.alt;
}