H5缩略图全屏放大并左右滑动实现(适配H5和PC)
最近做H5遇到一个任务:点击页面缩略图全屏放大,并要支持左右滑动切换大图。这里特地记录一下:
先看高清无码效果图:
首先,创建缩略图容器:
<div id="thumbs"> <a href="img/1.jpg" style="background-image:url(img/1.jpg)" title="风景一"></a> <a href="img/2.jpg" style="background-image:url(img/2.jpg)" title="风景二"></a> <a href="img/3.jpg" style="background-image:url(img/3.jpg)" title="风景三"></a> <a href="img/4.jpg" style="background-image:url(img/4.jpg)" title="风景四"></a> <a href="img/5.jpg" style="background-image:url(img/5.jpg)" title="风景五"></a> <a href="img/6.jpg" style="background-image:url(img/6.jpg)" title="风景六"></a> <a href="img/7.jpg" style="background-image:url(img/7.jpg)" title="风景七"></a> <a href="img/8.jpg" style="background-image:url(img/8.jpg)" title="风景八"></a> <a href="img/9.jpg" style="background-image:url(img/9.jpg)" title="风景九"></a> </div>
之后,用户点击某张缩略图时触发JS动态创建全屏弹层,并自动加载相邻前一张后一张大图:
items.on('click', function(e){ e.preventDefault(); // Find the position of this image // in the collection index = items.index(this); showOverlay(index); showImage(index); // Preload the next image preload(index+1); // Preload the previous preload(index-1); });
接下来实现左右滑动切换:
// Listen for touch events on the body and check if they // originated in #gallerySlider img - the images in the slider. var startX;// original position $('body').on('touchstart', '#gallerySlider img', function(e){ var touch = e.originalEvent; startX = touch.changedTouches[0].pageX; slider.on('touchmove',function(e){ e.preventDefault(); touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; if(touch.pageX - startX > 10){ slider.off('touchmove'); showPrevious(); } else if (touch.pageX - startX < -10){ slider.off('touchmove'); showNext(); } }); // Return false to prevent image // highlighting on Android return false; }).on('touchend',function(e){ slider.off('touchmove'); // Hide the gallery if the images is touched / clicked, but not slide touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]; if(touch.pageX - startX == 0){ hideOverlay(); } });
为了适配PC网页,可以检测下当前设备支持滑动与否,否的话,弹层大图左右加入切换按钮,里面变轮播图效果:
// If the browser does not have support // for touch, display the arrows if ( !("ontouchstart" in window) ){ overlay.append(prevArrow).append(nextArrow); prevArrow.click(function(e){ e.preventDefault(); showPrevious(); }); nextArrow.click(function(e){ e.preventDefault(); showNext(); }); $('body').on('click', '#gallerySlider img', function(e){ e.preventDefault(); hideOverlay(); }); }
有时候图片数量多的话,查看大图还需要页码或者底部显示缩略图:
// Show index in the overlay page if(showIndex){ photoNum.appendTo(overlay); setSumPhotoNum(items); } // Add thumbholders to the overlay page if(showThumbs){ photoThumbs.find('ul').append(thumbholders); photoThumbs.find('li').on('click',function(e){ e.preventDefault(); index = thumbholders.index(this); jumpTo(index); }); photoThumbs.appendTo(overlay); }
OK,以上是大致的功能点实现,具体细节见源码index.js。