首页 > 解决方案 > 如何在图像单击时打开图像模式

问题描述

我一直在研究标记图像的代码。首先,我在屏幕上显示一组图像,单击时应打开一个模式。

我尝试了以下代码:

  <div id="gallery ">

   <?php
     foreach ($gallery as $i) {
    ?>
    <img href="#myModal" data-toggle="modal" data-target="#myModal" src="<?php echo "$i"; ?>" class="modal_img">

   <?php }
    ?>
   </div>

上面的代码用于显示数组中的一组图像。以下代码我试图创建一个模态:

  <div id="myModal" class="modal">

    <!-- The Close Button -->
    <span class="close">&times;</span>
   <input type="hidden" id="result"></input>

   <!-- Modal Content (The Image) -->
  <div id="imagearea" class="imagearea">

  <span class="right_sec_text">Draw a Box over what captured your attention</span>

  <img class="modal-content" id="img01">
  </div>
   <div class="footer_btn">
    <p><button class="btn_success" id="btn_add" value="add areas">Confirm</button>
  </div>
  </div>

图像:显示带有图像的屏幕 在此处输入图像描述

因此,当单击图像时,模式应该打开。我尝试使用以下代码打开模式,但它没有响应。我试图在控制台日志中获取图像名,它可以工作。但模态不打开。

  $(function(){
     $(".modal_img").on("click",function(){
     var src = $(this).attr("src");
     $("#img01").prop("src",src);
     console.log(src);
    })
   })

CSS:

 #myModal {
 display: none; /* Hidden by default */
 position: fixed; /* Stay in place */
 z-index: 1; /* Sit on top */
 padding-top: 20px; /* Location of the box */
 left: 200px;
 top: 0;
 width: 60%; /* Full width */
 height: 100%; /* Full height */
 overflow: hidden; /* Enable scroll if needed */
 background-color: rgb(0,0,0); /* Fallback color */
 background:rgba(0,0,0,0.7); /* Black w/ opacity */
 }

 /* Modal Content (Image) */
.imagearea {
 display: flex;
flex-direction: column;
float: left;
margin-right:50px;
margin-left: 100px;
max-width: 100%;
position: absolute;
}

下图是预期的输出: 在此处输入图像描述

有人可以帮我解决这个问题。谢谢

标签: javascripthtmlbootstrap-modal

解决方案


要显示您的模式,您必须更改您的 javascript 代码

$(function(){
let modal = $('#myModal')     
$(".modal_img").on("click",function(){
     var src = $(this).attr("src");
     modal.css({"display": "block"});
     $("#img01", modal).prop("src",src);
     console.log(src);
    })
   });

推荐阅读