返回

javascript-如何让 JS 显示不同的图像

发布时间:2022-08-11 01:47:01 225
# 前端

我用这个脚本来显示带有图像的模式,但我想这样做,弹出的模式将显示按下的特定图像。

问题是JS只响应第一个img,但当我将第二个img添加到脚本中时,它只是不起作用。。。有没有简单的方法让JS为每个img工作,或者我需要为每个img编写整个脚本?

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

var img = document.getElementById("myImg");
var modalImg = document.getElementById("img1"); // second img (img1)
var modalImg = document.getElementById("img2"); // second img (img2)

img.onclick = function() {
  modal.style.display = "block";
  modalImg.src = this.src;
}

var span = document.getElementsByClassName("close")[0];

span.onclick = function() {
  modal.style.display = "none";
}
#myImg {
  border-radius: 5px;
  cursor: pointer;
  transition: 0.3s;
}

#myImg:hover {
  opacity: 0.7;
}

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.9);
}

.modal-content {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

.modal-content,
{
  animation-name: zoom;
  animation-duration: 0.6s;
}

@keyframes zoom {
  from {
    transform: scale(0)
  }
  to {
    transform: scale(1)
  }
}

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

.close:hover,
.close:focus {
  color: #bbb;
  text-decoration: none;
  cursor: pointer;
}

@media only screen and (max-width: 700px) {
  .modal-content {
    width: 100%;
  }
}
<div> <img src="https://picsum.photos/id/237/150/150" id="myImg"> <div id="myModal" class="modal"> <span class="close"> &times; </span> <img class="modal-content" id="img1"> </div> </div> <div> <img src="https://picsum.photos/id/137/150/150" id="myImg"> <div id="myModal" class="modal"> <span class="close"> &times; </span> <img class="modal-content" id="img2"> </div>
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(2)
按点赞数排序
用户头像