[英]Javascript Lightbox, Show Caption and Keyboard Navigation problem
我有這個javascript燈箱,但有兩個問題。 首先,我可能犯了一個錯誤,它應該顯示圖像的替代文本。
function openGallery($gallery, imageIndex = 0) {
const $galleryThumbnails = $gallery.find('img');
const $galleryElement = $(`
<div class="gallery-lightbox">
<button class="gallery-close">✖</button>
<button class="gallery-next">❱</button>
<button class="gallery-preview">❰ </button>
<div class="gallery-image-container">
<img src="" alt="">
</div>
<div class="gallery-status"></div>
</div>
`);
$galleryElement.prependTo(document.body);
// This part shows the image
function showFullImage(){
const fullImageUrl = $galleryThumbnails
.eq(imageIndex)
.attr('data-full-image');
$galleryElement
.find('.gallery-image-container > img')
.attr('src', fullImageUrl);
// Show Text Code that don't work
$galleryElement
.find('.gallery-image-container > img')
.attr('alt', alt);
}
其次,對於鍵盤導航,我還想用esc關閉圖庫。 我嘗試了幾種方法,但沒有成功。 有人可以提出解決方案嗎?
function nextSlide() {
imageIndex = (imageIndex + 1) % $galleryThumbnails.length;
showFullImage();
}
$galleryElement
.find('.gallery-next')
.click(() => nextSlide());
$galleryElement
.find('.gallery-preview')
.on('click', () => {
imageIndex = imageIndex === 0 ? $galleryThumbnails.length - 1 :
imageIndex - 1;
showFullImage();
});
$galleryElement
.find('.gallery-close')
.click(() => $galleryElement.remove());
showFullImage();
}
// Code for keyboard navigation
document.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == 37) {
document.querySelector('.gallery-next').click();
}
else if (e.keyCode == 39) {
document.querySelector('.gallery-preview').click();
}
};
$('[data-gallery] > img')
.click((event) => {
const $gallery = $(event.target).parent();
const $items = $gallery.find('img');
const index = $items.index(event.target);
openGallery($gallery, index);
});
要將alt文本添加到圖像中,可以使用alt屬性或setAttribute方法,例如:
image.alt = "Alt text here";
要么
image.setAttribute("alt","Alt text here");
要使用esc鍵,您必須執行以下操作:
$(document).bind('keydown', function(e) {
if (e.which == 27) {
alert('Pressed esc key!');
}
});
或使用keyup事件,例如:
$(document).keyup(function(e){
if (e.which == 27) {
alert('Pressed esc key!');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.