我目前正在研究一个简单的图像模式,该模式应该只显示带有关闭按钮的图像缩放。我有一个从CMS生成的标记,其中可以将标记配置为具有一个额外的类“ lightbox”作为属性,然后再触发lightbox脚本。
但是,目前看来,它仅适用于已加载的第一张图像。当我单击另一张图像时,它显示的是与第一张图像相同的图像源,我不确定如何修复它。是否需要首先循环播放所有图像?
我的CMS为DOM中的此类图像生成标记(图像是占位符:]
<a href="image1.png" class="lightbox">
<img class="image-embed-item" src="image" >
</a>
<a href="image1.png" class="lightbox">
<img class="image-embed-item" src="image" >
</a>
<a href="image1.png" class="lightbox">
<img class="image-embed-item" src="image" >
</a>
然后在我的默认布局中,为灯箱模式添加标记:
<div id="imagemodal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="close">×</div>
<img src="" id="imagepreview" style="width: 100%;" >
</div>
</div>
这是JavaScript代码:
window.addEventListener('DOMContentLoaded', function () {
// add imageresource id to loaded image
$(".image-embed-item").attr("id", "imageresource");
// add data-toggle class to all lightbox elements
$(".lightbox").attr("data-toggle", "lightbox");
// click event for data toggle
$(document).on('click', '[data-toggle="lightbox"]', function (event) {
event.preventDefault();
// use image source from clicked image
$('#imagepreview').attr('src', $('#imageresource').attr('src'));
$('.modal').css('display', 'block');
});
$(document).on('click', $('.closeModal'), function (event) {
// close function
});
});
这是我的CSS:
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1000; /* Sit on top */
left: 0;
top: 0;
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.4); /* Black w/ opacity */
}
/* Modal Content/Box */
.modal-content {
background-color: #fefefe;
margin: 15% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%; /* Could be more or less, depending on screen size */
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
您对以下所有.image-embed-item
使用相同的ID:
$(".image-embed-item").attr("id", "imageresource");
然后使用$('#imageresource').attr('src')
设置预览。这就是为什么它总是显示模态中的第一张图像。您可以通过将$('#imageresource').attr('src')
更改为$(this).find('img').attr('src')
来解决。像这样的东西:
window.addEventListener('DOMContentLoaded', function () {
// add data-toggle class to all lightbox elements
$(".lightbox").attr("data-toggle", "lightbox");
// click event for data toggle
$(document).on('click', '[data-toggle="lightbox"]', function (event) {
event.preventDefault();
// use image source from clicked image
$('#imagepreview').attr('src', $(this).find('img').attr('src'));
$('.modal').css('display', 'block');
});
$(document).on('click', $('.closeModal'), function (event) {
// close function
});
});