以弹出模式打开图片

时间:2018-12-11 13:45:04

标签: javascript jquery html css popup

我希望得到您的帮助,以便处理HTML模板中的图片。 我正在使用Django 1.11.16,CSS3和JavaScript。

id托管看起来像这样:#myimg_idid每个图像都有一个唯一的整数值。我在HTML模板中显示这样的图片:

<img class="popup_image" id="myimg_{{ element.publication.id }}" src="{{ element.publication.cover.url }}">

<div id="myModal2" class="modal2">
    <span class="close">&times;</span>
    <img class="modal2-content" id="imgmodal_{{ element.publication.id }}">
</div>

<script>
// Get the modal
var modal = document.getElementById('myModal2');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img2 = document.getElementById('myimg_{{element.publication.id}}');
console.log(img2);
var modalImg = document.getElementById("imgmodal_{{element.publication.id}}");
console.log(modalImg);
img2.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
console.log(modalImg.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";
}
</script>

我添加了带有属性选择器的CSS部分,以便处理动态id

<style>
    /* Style the Image Used to Trigger the Modal */
    img[id^="myimg"] {
      border-radius: 5px;
      cursor: pointer;
      transition: 0.3s;
    }

    img[id^="myimg"]:hover {
      opacity: 0.7;
    }

    /* The Modal (background) */
    .modal2 {
      display: none; /* Hidden by default */
      position: fixed; /* Stay in place */
      z-index: 1; /* Sit on top */
      padding-top: 100px; /* Location of the box */
      left: 0;
      top: 14%;
      width: 100%; /* Full width */
      height: 100%; /* Full height */
      overflow: auto; /* Enable scroll if needed */
      background-color: rgb(0, 0, 0); /* Fallback color */
      background-color: rgba(0, 0, 0, 0.9); /* Black w/ opacity */
    }

    /* Modal Content (Image) */
    .modal2-content {
      margin: auto;
      display: block;
      width: 80%;
      max-width: 700px;
      animation-name: zoom;
      animation-duration: 0.6s;
    }

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

    /* The Close Button */
    .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;
    }

    /* 100% Image Width on Smaller Screens */
    @media only screen and (max-width: 700px) {
      .modal2-content {
        width: 100%;
      }
    }
  </style>

当我单击图片时,背景变暗,出现关闭按钮,但我的模态中没有图片。我不知道问题出在哪里。

一个例子:

enter image description here

非常感谢您!

0 个答案:

没有答案