在Bootstrap中打开放大图片的模态框

67

如何使用jQuery / JS在模态框中打开/放大图像,而不是使用数据属性?

每当用户将图像插入内容编辑器时,我需要使其可点击并能够通过JS在模态框中展开,因此我不能依赖于用户输入他们不知道如何使用的数据属性。

我尝试过:

<a href="/myImage.png" id="pop">
    <img src="/myImage.png" style="width: 400px; height: 264px;">
    Click to Enlarge
</a>

jQuery :-


jQuery是一种广泛使用的JavaScript库,用于简化在网页中操作HTML元素、处理事件、执行动画和处理AJAX等常见任务的过程。它是免费且开源的。
$("#pop").on("click", function() {
   $(this).modal();
});

我需要在jQuery中添加信息以传递图像源以出现在模态窗口中吗?

谢谢!!!


当用户在弹出窗口中点击时,设置模态图像源=他们想要放大的图像源。 - Jordan.J.D
@JordanD 感谢您的回复!在代码中具体是什么样子呢? - Jibes
当用户在内容编辑器中插入图像时,您需要在用户单击插入到编辑器中的图像时显示该图像吗? - martinezjc
@martinezjc 是的,使用内容管理系统,并希望在通过内容编辑器插入图像时随时具有此功能。 - Jibes
有没有一种方法可以在不使用JQuery和JS的情况下实现这个功能?只用CSS? - Paula
10个回答

153
如果您正在使用bootstrap 3,可以尝试以下代码:
HTML
<a href="#" id="pop">
    <img id="imageresource" src="http://patyshibuya.com.br/wp-content/uploads/2014/04/04.jpg" style="width: 400px; height: 264px;">
    Click to Enlarge
</a>
    
<!-- Creates the bootstrap modal where the image will appear -->
<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">Image preview</h4>
      </div>
      <div class="modal-body">
        <img src="" id="imagepreview" style="width: 400px; height: 264px;" >
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

JavaScript:

$("#pop").on("click", function() {
   $('#imagepreview').attr('src', $('#imageresource').attr('src')); // here asign the image to the modal when the user click the enlarge link
   $('#imagemodal').modal('show'); // imagemodal is the id attribute assigned to the bootstrap modal, then i use the show function
});

这是可运行的fiddle


1
我找到了为什么其他图像无法在模态中打开的原因,因为弹出框的ID是唯一的,所以我将其更改为类。现在唯一的问题是其他模态中的图像源显示第一张图像,而不是单击的图像! - Jibes
2
我做了一个更新,现在它可以工作了。问题是.pop img总会取第一个被赋予类名.pop的图片,所以我只需要使用$('.imagepreview').attr('src', $(this).find('img').attr('src'));从当前的<a>标签中获取实际的图片(<img>)并将其赋值给模态框内的图像属性src。请将我的答案标记为解决方案。这是您的fiddle链接,现在已经可以正常工作:http://jsfiddle.net/6CR2H/1/ :) - martinezjc
1
你真是个救星!谢谢你抽出时间帮助我,你真是太慷慨了! - Jibes
1
你的意思是从图片而不是链接触发事件吗?还是从包含图片的 div 触发事件,@stom? - martinezjc
3
@stom,基本思路是一样的。点击事件是基于元素的class属性而不是HTML标签<a>来工作的。这是示例代码:http://jsfiddle.net/oLwzepfc/ - martinezjc
显示剩余6条评论

14

我稍微改动了一下,但仍然做不到某些事情。

我添加了点击它关闭它的功能 - 这很简单但非常实用。

 <div class="modal-dialog" data-dismiss="modal">

每张照片下面需要不同的描述。我在页脚中添加了描述,只是为了展示我需要的东西。 它需要随着每张照片而改变。

HTML

<div class="modal fade" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" data-dismiss="modal">
      <div class="modal-content"  >              
        <div class="modal-body">
          <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
             <img src="" class="imagepreview" style="width: 100%;" >
        </div> 
     <div class="modal-footer">
       <div class="col-xs-12">
           <p class="text-left">1. line of description<br>2. line of description <br>3. line of description</p>
       </div>
     </div>         
   </div>
 </div>

JavaScript:

$(function() {
    $('.pop').on('click', function() {
        $('.imagepreview').attr('src', $(this).find('img').attr('src'));
        $('#imagemodal').modal('show');   
    });     
});

如果窗口只在全屏状态下打开,那就更好了。因为图片及其描述的大小超过了屏幕尺寸,导致窗口出现滚动。如果屏幕比图片要大很多,它应该仅停留在原始大小,例如900像素高度,而不再变大。

http://jsfiddle.net/2ve4hbmm/


6

我知道你的问题被标记为bootstrap-modal(尽管你没有明确提到Bootstrap),但我很喜欢看到W3.CSS解决这个问题的简单方式,我认为与大家分享是很好的。

  <img src="/myImage.png" style="width:30%;cursor:zoom-in"
  onclick="document.getElementById('modal01').style.display='block'">

  <div id="modal01" class="w3-modal" onclick="this.style.display='none'">
    <div class="w3-modal-content w3-animate-zoom">
      <img src="/myImage.png" style="width:100%">
    </div>
  </div>

这里是一个指向W3Schools modal image例子的链接,用于查看头部信息以使W3.CSS生效。 modal image

6

3

这是我使用的Bootstrap 5解决方案。

<!-- a link that triggers modal -->
<a href="#myModal" type="" class="" data-bs-toggle="modal" data-bs-target="#myModal">More details</a>

<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Image Title</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <!--        include image here-->
        <img src="images/img_example_8.png" alt="Image Title" class="img-fluid">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

最受欢迎的解决方法对我无效,因为它使用了Bootstrap 3,而我的应用程序没有。基本上,我只是按照Bootstrap 5模态框文档进行操作。我将模态框大小设置为大,这样图像就会更大。


1

我已经在jsfiddle中为您准备了一个非常简单的模态框,供您参考。

JSFiddle

$("#pop").on("click", function(e) {
  // e.preventDefault() this is stopping the redirect to the image its self
  e.preventDefault();
  // #the-modal is the img tag that I use as the modal.
  $('#the-modal').modal('toggle');
});

你缺少的部分是当链接被点击时想要显示的隐藏模态框。在这个例子中,我使用了第二张图片作为模态框,并添加了Bootstap类。

1
    <div class="row" style="display:inline-block">

    <div class="col-lg-12">
        <h1 class="page-header">Thumbnail Gallery</h1>

            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="This is my title" data-caption="Some lovely red flowers" data-image="http://onelive.us/wp-content/uploads/2014/08/flower-delivery-online.jpg" data-target="#image-gallery">
                <img class="img-responsive" src="http://onelive.us/wp-content/uploads/2014/08/flower-delivery-online.jpg" alt="Short alt text">
            </a>
        </div>
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="The car i dream about" data-caption="If you sponsor me, I can drive this car" data-image="http://www.picturesnew.com/media/images/car-image.jpg" data-target="#image-gallery">
                <img class="img-responsive" src="http://www.picturesnew.com/media/images/car-image.jpg" alt="A alt text">
            </a>
        </div>
            <div class="col-lg-3 col-md-4 col-xs-6 thumb">
            <a class="thumbnail" href="#" data-image-id="" data-toggle="modal" data-title="Im so nice" data-caption="And if there is money left, my girlfriend will receive this car" data-image="http://upload.wikimedia.org/wikipedia/commons/7/78/1997_Fiat_Panda.JPG" data-target="#image-gallery">
                <img class="img-responsive" src="http://upload.wikimedia.org/wikipedia/commons/7/78/1997_Fiat_Panda.JPG" alt="Another alt text">
            </a>
        </div>
</div>


<div class="modal fade" id="image-gallery" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title" id="image-gallery-title"></h4>
            </div>
            <div class="modal-body">
                <img id="image-gallery-image" class="img-responsive" src="">
            </div>
            <div class="modal-footer">

                <div class="col-md-2">
                    <button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>
                </div>

                <div class="col-md-8 text-justify" id="image-gallery-caption">
                    This text will be overwritten by jQuery
                </div>

                <div class="col-md-2">
                    <button type="button" id="show-next-image" class="btn btn-default">Next</button>
                </div>
            </div>
        </div>
    </div>
</div>



<script>
$(document).ready(function(){

    loadGallery(true, 'a.thumbnail');

    //This function disables buttons when needed
    function disableButtons(counter_max, counter_current){
        $('#show-previous-image, #show-next-image').show();
        if(counter_max == counter_current){
            $('#show-next-image').hide();
        } else if (counter_current == 1){
            $('#show-previous-image').hide();
        }
    }

    /**
     *
     * @param setIDs        Sets IDs when DOM is loaded. If using a PHP counter, set to false.
     * @param setClickAttr  Sets the attribute for the click handler.
     */

    function loadGallery(setIDs, setClickAttr){
        var current_image,
            selector,
            counter = 0;

        $('#show-next-image, #show-previous-image').click(function(){
            if($(this).attr('id') == 'show-previous-image'){
                current_image--;
            } else {
                current_image++;
            }

            selector = $('[data-image-id="' + current_image + '"]');
            updateGallery(selector);
        });

        function updateGallery(selector) {
            var $sel = selector;
            current_image = $sel.data('image-id');
            $('#image-gallery-caption').text($sel.data('caption'));
            $('#image-gallery-title').text($sel.data('title'));
            $('#image-gallery-image').attr('src', $sel.data('image'));
            disableButtons(counter, $sel.data('image-id'));
        }

        if(setIDs == true){
            $('[data-image-id]').each(function(){
                counter++;
                $(this).attr('data-image-id',counter);
            });
        }
        $(setClickAttr).on('click',function(){
            updateGallery($(this));
        });
    }
});
</script>

0

如果你有一个编辑器,这意味着图像是由Javascript动态添加的,因此在使用jQuery时,你需要从页面中已经存在的对象开始选择图像标签。

我的答案适用于两种情况:页面加载时显示的图像和Javascript动态添加的图像。

我正在使用一个可以添加并将图像打开到模态框的类。

图片:

<img src='/assets/image.png' style='width:100px;' class='imageViewBig'/>

模态框:

<div class="modal fade" id="modalImgageView" tabindex="-1" aria-hidden="true">
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-body text-center">
            <button type="button" class="btn-close bg-dark" data-bs-dismiss="modal" aria-label="Close" style="position:absolute; top:5px;right:5px;"></button>
            <img src="assets/images/nophoto.png" alt="Image Title" class="img-fluid" id="modalImgageViewIMG">
        </div>
    </div>
</div></div>
  • 模态框的标题和页脚已经移除
  • “关闭”按钮已经移到右上角图片旁边
  • 来自模态框的图片有ID“modalImgageViewIMG”,需要更改“src”属性

jQuery代码:

$(document).on("click", ".imageViewBig", function() {
    let url = $(this).attr('src');
    $('#modalImgageViewIMG').attr('src', url);
    $('#modalImgageView').modal('toggle');

});
  • 在 $(document) 上设置了 click 事件
  • class "imageViewBig" 有一个 "click" 事件监听器,将从所点击的图像中获取 "src" 并将其放置到模态框中的图像上

0

css:

img.modal-img {
  cursor: pointer;
  transition: 0.3s;
}
img.modal-img:hover {
  opacity: 0.7;
}
.img-modal {
  display: none;
  position: fixed;
  z-index: 99999;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.9);
}
.img-modal img {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700%;
}
.img-modal div {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}
.img-modal img, .img-modal div {
  animation: zoom 0.6s;
}
.img-modal span {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
  cursor: pointer;
}
@media only screen and (max-width: 700px) {
  .img-modal img {
    width: 100%;
  }
}
@keyframes zoom {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}

Javascript:

$('img.modal-img').each(function() {
    var modal = $('<div class="img-modal"><span>&times;</span><img /><div></div></div>');
    modal.find('img').attr('src', $(this).attr('src'));
    if($(this).attr('alt'))
      modal.find('div').text($(this).attr('alt'));
    $(this).after(modal);
    modal = $(this).next();
    $(this).click(function(event) {
      modal.show(300);
      modal.find('span').show(0.3);
    });
    modal.find('span').click(function(event) {
      modal.hide(300);
    });
  });
  $(document).keyup(function(event) {
    if(event.which==27)
      $('.img-modal>span').click();
  });
img.modal-img {
  cursor: pointer;
  transition: 0.3s;
}
img.modal-img:hover {
  opacity: 0.7;
}
.img-modal {
  display: none;
  position: fixed;
  z-index: 99999;
  padding-top: 100px;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.9);
}
.img-modal img {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700%;
}
.img-modal div {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
  text-align: center;
  color: #ccc;
  padding: 10px 0;
  height: 150px;
}
.img-modal img, .img-modal div {
  animation: zoom 0.6s;
}
.img-modal span {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
  cursor: pointer;
}
@media only screen and (max-width: 700px) {
  .img-modal img {
    width: 100%;
  }
}
@keyframes zoom {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}
Javascript:

$('img.modal-img').each(function() {
    var modal = $('<div class="img-modal"><span>&times;</span><img /><div></div></div>');
    modal.find('img').attr('src', $(this).attr('src'));
    if($(this).attr('alt'))
      modal.find('div').text($(this).attr('alt'));
    $(this).after(modal);
    modal = $(this).next();
    $(this).click(function(event) {
      modal.show(300);
      modal.find('span').show(0.3);
    });
    modal.find('span').click(function(event) {
      modal.hide(300);
    });
  });
  $(document).keyup(function(event) {
    if(event.which==27)
      $('.img-modal>span').click();
  });

HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<img src="http://www.google.com/favicon.ico" class="modal-img">


style="display:inline-block" - mirazimi

-1

以上两个不运行。

表格编辑按钮:

<a data-toggle="modal" type="edit" id="{{$b->id}}" data-id="{{$b->id}}"  data-target="#form_edit_masterbank" data-bank_nama="{{ $b->bank_nama }}" data-bank_accnama="{{ $b->bank_accnama }}" data-bank_accnum="{{ $b->bank_accnum }}" data-active="{{ $b->active }}" data-logobank="{{asset('components/images/user/masterbank/')}}/{{$b->images}}" href="#"  class="edit edit-masterbank"   ><i class="fa fa-edit" ></i></a>                                               

然后在 JavaScript 中:

$('.imagepreview555').attr('src', logobank);

然后在HTML中:

<img src="" class="imagepreview555"  style="width: 100%;" />

它没有运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接