【发布时间】:2014-09-23 18:14:46
【问题描述】:
我正在从头开始创建类似灯箱的功能。到目前为止,我已经让接管元素正常工作并正确显示图像,但现在我想编写下一个/上一个按钮。我还希望按钮循环浏览图库(如果在第一张图片上单击“上一张”,则会加载最后一张图片,反之亦然)。
这是显示我的图像缩略图的 HTML:
<div id="gallery-wrapper">
<ul>
<li><a href="/path/to/large/image" class="image"><img src="/path/to/thumbnail" alt="Image" /></a></li>
<li><a href="/path/to/large/image" class="image"><img src="/path/to/thumbnail" alt="Image" /></a></li>
<li><a href="/path/to/large/image" class="image"><img src="/path/to/thumbnail" alt="Image" /></a></li>
<li><a href="/path/to/large/image" class="image"><img src="/path/to/thumbnail" alt="Image" /></a></li>
</ul>
</div>
点击图片缩略图时,会生成灯箱并通过 Javascript 显示:
$(document).ready(function() {
$('.image').click(function(e) {
e.preventDefault();
$('body').width($('body').width());
$('body').css('overflow', 'hidden');
var image_href = $(this).attr("href");
if ($('#lightbox').length > 0) {
$('#content').html('<img src="' + image_href + '" />');
$('#lightbox').show();
}
else {
var lightbox =
'<div id="lightbox">' +
'<div id="content">' +
'<div class="close-gallery">Close<span>X</span></div>'+
'<div class="gallery-previous"></div>'+
'<img src="'+ image_href +'" />' +
'<div class="gallery-next"></div>'+
'</div>' +
'</div>';
$('body').append(lightbox);
}
});
$('body').on('click', '.close-gallery', function () {
$('body').removeAttr('style');
$('#lightbox').remove();
});
});
这是我迄今为止尝试过的。它仅适用于当前所选图像之前或之后的兄弟:
$(document).ready(function($) {
$('.image').click(function(e) {
$(this).addClass('active');
e.preventDefault();
$('body').width($('body').width());
$('body').css('overflow', 'hidden');
var image_href = $(this).attr("href");
var prevImage = $('.active').parent().prev().find('a').attr("href");
var nextImage = $('.active').parent().next().find('a').attr("href");
console.log(prevImage, nextImage);
if ($('#lightbox').length > 0) {
$('#content').html('<img src="' + image_href + '" />');
$('#lightbox').show();
}
else {
var lightbox =
'<div id="lightbox">' +
'<div id="content">' +
'<div class="close-gallery">Close<span>X</span></div>'+
'<div class="gallery-previous" data-nav="'+ prevImage +'"></div>'+
'<img src="'+ image_href +'" />' +
'<div class="gallery-next" data-nav="'+ nextImage +'"></div>'+
'</div>' +
'</div>';
$('body').append(lightbox);
}
});
$('body').on('click', '.gallery-previous', function () {
var prev = $(this).data('nav');
console.log(prev);
$('#content').find('img').attr('src',prev);
});
$('body').on('click', '.gallery-next', function () {
var next = $(this).data('nav');
console.log(next);
$('#content').find('img').attr('src',next);
});
$('body').on('click', '.close-gallery', function () {
$('body').removeAttr('style');
$('#lightbox').remove();
});
});
我的想法是用下一个/上一个图像链接替换当前的灯箱图像src,但我无法弄清楚我将如何实际实现这一点。任何帮助都非常感谢!
【问题讨论】:
-
不清楚你在哪里绊倒了。您是否尝试使用
.attr()? -
刚刚用我迄今为止尝试过的内容更新了我的问题。我确实尝试使用
.attr()/.data(),但它仅适用于当前所选图像之前和之后的兄弟姐妹,因为next和prev变量是在初始单击图像时设置的。
标签: javascript jquery image