image1 image2 image3

以上面的html为例,利用jQuery实现图片灯箱效果,且带鼠标点击图片轮换上下图、鼠标手势滑动图片上下图,键盘方向键上下图,显示当前图片名字和所在索引位置,且首尾循环内容: // 首先,定义一个变量来存储当前显示的图片的索引位置 let currentIndex = 0;

// 获取所有图片元素和灯箱元素 const $images = $('.image-list img'); const $lightbox = $('.lightbox'); const $lightboxImg = $lightbox.find('img'); const $lightboxInfo = $lightbox.find('.info');

// 点击图片时,显示灯箱并且显示当前点击的图片 $images.on('click', function() { // 获取图片的索引位置 currentIndex = $images.index($(this)); // 设置灯箱图片的 src 属性 $lightboxImg.attr('src', $(this).parent().attr('href')); // 显示灯箱 $lightbox.show(); // 更新灯箱信息 updateLightboxInfo(); });

// 点击关闭按钮时,隐藏灯箱 $lightbox.find('.close').on('click', function() { $lightbox.hide(); });

// 点击上一张图片按钮时,显示上一张图片 $lightbox.find('.prev').on('click', function() { currentIndex = (currentIndex - 1 + $images.length) % $images.length; $lightboxImg.attr('src', $images.eq(currentIndex).parent().attr('href')); updateLightboxInfo(); });

// 点击下一张图片按钮时,显示下一张图片 $lightbox.find('.next').on('click', function() { currentIndex = (currentIndex + 1) % $images.length; $lightboxImg.attr('src', $images.eq(currentIndex).parent().attr('href')); updateLightboxInfo(); });

// 当用户按下键盘方向键时,显示上一张或下一张图片 $(document).on('keydown', function(event) { if (event.keyCode === 37) { // 左箭头键 $lightbox.find('.prev').trigger('click'); } else if (event.keyCode === 39) { // 右箭头键 $lightbox.find('.next').trigger('click'); } });

// 当用户用鼠标拖动灯箱图片时,判断是向上滑动还是向下滑动,并显示相应的图片 let startY = 0; let endY = 0; $lightboxImg.on('mousedown touchstart', function(event) { startY = event.pageY || event.originalEvent.touches[0].pageY; }); $lightboxImg.on('mouseup touchend', function(event) { endY = event.pageY || event.originalEvent.changedTouches[0].pageY; if (startY - endY > 50) { // 向上滑动 $lightbox.find('.prev').trigger('click'); } else if (endY - startY > 50) { // 向下滑动 $lightbox.find('.next').trigger('click'); } });

// 更新灯箱信息 function updateLightboxInfo() { $lightboxInfo.text('Image ' + (currentIndex + 1) + ' of ' + $images.length + ': ' + $images.eq(currentIndex).attr('alt')); }

jQuery 图片灯箱效果实现 - 鼠标点击/滑动/键盘切换图片

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

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