如何在灯箱中动态添加图像

时间:2016-12-28 13:49:19

标签: jquery dynamic lightbox

我已经搜索并查看了lightbox 2: how to add dynamically images via javascript提供的答案,但这对我不起作用。任何人都可以给我一个代码的例子,它在灯箱中添加图像时工作正常。我正在使用lokesh灯箱。

1 个答案:

答案 0 :(得分:0)

我使用这个简单的解决方案。

Requeriments:

  • 基本Html
  • 基本CSS
  • 基本Js
  • 自举
  • 的jQuery

示例Html代码:

<div class="container"> <!-- image area container -->
<div class="col-xs-6 col-sm-3"> <!-- Duplicate this div and change , or generate from each/loop with dynamic content  -->
<a href="#" class="thumbnail" data-toggle="modal" data-target="#lightbox"> 
<img src="http://myexample.org/uploads/images/test.jpg" alt="..."> <!-- change just image url and alt attribute -->
</a>
</div>
</div>
<!-- lightbox div -->
<div id="lightbox" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<button type="button" class="close hidden" data-dismiss="modal" aria-hidden="true">×</button>
<div class="modal-content">
<div class="modal-body">
<img src="" alt="" /> <!-- this IMG tag receives dynamic image data/info -->
</div>
</div>
</div>

CSS示例:

body {
padding: 30px 0px;
}
#lightbox .modal-content {
display: inline-block;
text-align: center;   
}
#lightbox .close {
opacity: 1;
color: rgb(255, 255, 255);
background-color: rgb(25, 25, 25);
padding: 5px 8px;
border-radius: 30px;
border: 2px solid rgb(255, 255, 255);
position: absolute;
top: -15px;
right: -55px;
z-index:1032;
}

** JS Sample ***

$(document).ready(function() {

// Change image in lightbox based on click event
var $lightbox = $('#lightbox');
$('[data-target="#lightbox"]').on('click', function(event) {
var $img = $(this).find('img'), 
src = $img.attr('src'),
alt = $img.attr('alt'),
css = {
'maxWidth': $(window).width() - 100,
'maxHeight': $(window).height() - 100
};

// find and change attributes
$lightbox.find('.close').addClass('hidden');
$lightbox.find('img').attr('src', src);
$lightbox.find('img').attr('alt', alt);
$lightbox.find('img').css(css);
});

// show modal as lightbox with clicked image
$lightbox.on('shown.bs.modal', function (e) {
var $img = $lightbox.find('img');
$lightbox.find('.modal-dialog').css({'width': $img.width()});
$lightbox.find('.close').removeClass('hidden');
});
});

您可以尝试在此链接中运行此代码: http://bootsnipp.com/user/snippets/86R0Z

我希望这对你有所帮助。

最好的问候。