jQuery 实现图片灯箱效果 - 鼠标点击、手势滑动、键盘控制

本文将介绍如何使用 jQuery 实现一个图片灯箱效果,该效果支持鼠标点击图片轮换上下图、鼠标手势滑动图片上下图、键盘方向键上下图,并显示当前图片名字和所在索引位置,且首尾循环内容。

HTML 结构

<div class='image-list'>
  <a href='cc1.jpg'><img src='cc1-thumb.jpg' alt='image1'></a>
  <a href='cc2.jpg'><img src='cc2-thumb.jpg' alt='image2'></a>
  <a href='cc3.jpg'><img src='cc3-thumb.jpg' alt='image3'></a>
</div>

<div class='lightbox'>
  <img src='' alt='box'>
  <span class='close'>&times;</span>
  <span class='prev'>&lt;</span>
  <span class='next'>&gt;</span>
  <span class='info'></span>
</div>

jQuery 代码

$(function() {
  var $lightbox = $('.lightbox');
  var $imageList = $('.image-list');
  var $images = $imageList.find('img');
  var currentIndex = 0;
  var imageCount = $images.length;

  function updateLightbox() {
    $lightbox.find('img').attr('src', $images.eq(currentIndex).attr('src').replace('-thumb', ''));
    $lightbox.find('.info').text($images.eq(currentIndex).attr('alt') + ' (' + (currentIndex + 1) + ' of ' + imageCount + ')');
  }

  function showLightbox() {
    $lightbox.fadeIn();
    $('body').css('overflow', 'hidden');
    updateLightbox();
  }

  function hideLightbox() {
    $lightbox.fadeOut();
    $('body').css('overflow', 'auto');
  }

  function showPrevImage() {
    currentIndex = (currentIndex == 0) ? imageCount - 1 : currentIndex - 1;
    updateLightbox();
  }

  function showNextImage() {
    currentIndex = (currentIndex == imageCount - 1) ? 0 : currentIndex + 1;
    updateLightbox();
  }

  function handleKeydown(e) {
    if (e.keyCode == 27) { // ESC key
      hideLightbox();
    } else if (e.keyCode == 37) { // left arrow key
      showPrevImage();
    } else if (e.keyCode == 39) { // right arrow key
      showNextImage();
    }
  }

  $imageList.on('click', 'a', function(e) {
    e.preventDefault();
    currentIndex = $(this).index();
    showLightbox();
  });

  $lightbox.find('.close').on('click', hideLightbox);

  $lightbox.on('click', function(e) {
    if (e.target == this) {
      hideLightbox();
    }
  });

  $lightbox.find('.prev').on('click', showPrevImage);

  $lightbox.find('.next').on('click', showNextImage);

  $lightbox.on('swipeleft', showNextImage);

  $lightbox.on('swiperight', showPrevImage);

  $(document).on('keydown', handleKeydown);
});

手势滑动实现

需要使用 jQuery 插件来实现手势滑动的效果,可以使用如 hammer.js、touchSwipe 等插件。

总结

本文介绍了使用 jQuery 实现图片灯箱效果,并支持鼠标点击、手势滑动、键盘控制,以及首尾循环功能。希望本文能够帮助您快速搭建图片灯箱功能。

jQuery 实现图片灯箱效果 - 鼠标点击、手势滑动、键盘控制

原文地址: https://www.cveoy.top/t/topic/m8AD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录