Javascript 灯箱、显示标题和键盘导航问题

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 property or the 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!');
    }
});