简体   繁体   English

如何在图像单击时动态更改模态的内容

[英]how to dynamically change the content of modal on an Image click

I have the following 3 thumbnail images on an HTML page.我在 HTML 页面上有以下 3 个缩略图。 When the user clicks on any of these images, I want to show that particular image in a modal.当用户单击这些图像中的任何一个时,我想以模式显示该特定图像。

How can I dynamically pass the image name inside the modal-body, on every image click?如何在每次图像点击时动态传递模态体内的图像名称?

<a href="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
  <img src="images/Picture1.jpg" alt="image not available" onclick=check(this)>
</a>
<a href="images/Picture2.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
  <img src="images/Picture2.jpg" alt="image not available" onclick=check(this)>
</a>
<a href="images/Picture3.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
  <img src="images/Picture3.jpg" alt="image not available" onclick=check(this)>
</a>

Modal模态

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Image</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <img src="images/Picture1.jpg" alt="image not available" id="imagepreview" style="width: 100%; height: 100%;">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Js function which tells, which image is clicked Js function 告诉哪个图片被点击

function check(img) {
  var src = img.src.replace(/^.*[\\\/]/, "");
  console.log(src);
}

You can replace the src attribute of the image in your modal-body with the one of the image which was clicked:您可以将 modal-body 中图像的src属性替换为单击的图像之一:

function check(img) {
  document.getElementById("imagepreview").src = img.src;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM