最近做一个移动端图片页面,母页是一系列预览小图,点击某张小图后,需要满屏显示大图,并可以左右滑动来浏览其他大图;网上找了一下,找到了一个fotorama组件,感觉用起来效果不错,记录一下使用心得;
先从http://www.fotorama.io/set-up/下载fotorama包,在页面上导入CSS和JS,另外,fotorama依赖jquery框架,需要把jquery也引入进来;
在head中引入css:
<link href="js/fotorama.css" type="text/css" rel="stylesheet">
在body中引入js:
<script src="js/jquery-1.11.2.min.js"></script> <script src="js/fotorama.js"></script>
页面放入预览小图:
<div class="box"> <div class="pic"><img src="p_w_picpaths/1_s.jpg" /></div> <div class="pic"><img src="p_w_picpaths/2_s.jpg" /></div> <div class="pic"><img src="p_w_picpaths/3_s.jpg" /></div> <div class="pic"><img src="p_w_picpaths/4_s.jpg" /></div> <div class="pic"><img src="p_w_picpaths/5_s.jpg" /></div> <div class="pic"><img src="p_w_picpaths/6_s.jpg" /></div> </div> <div class="fotorama" data-max-width="100%"></div>
其中<div class="fotorama" data-max-width="100%"></div>是组件显示大图使用的;
然后调用组件的方法进行大图显示:
<script> //原始图片数据 var p_w_picpaths=[{url:'p_w_picpaths/1_b.jpg',thumb:'p_w_picpaths/1_s.jpg',title:'1.jpg'},{url:'p_w_picpaths/2_b.jpg',thumb:'p_w_picpaths/2_s.jpg',title:'2.jpg'},{url:'p_w_picpaths/3_b.jpg',thumb:'p_w_picpaths/3_s.jpg',title:'3.jpg'}, {url:'p_w_picpaths/4_b.jpg',thumb:'p_w_picpaths/4_s.jpg',title:'4.jpg'},{url:'p_w_picpaths/5_b.jpg',thumb:'p_w_picpaths/5_s.jpg',title:'5.jpg'},{url:'p_w_picpaths/6_b.jpg',thumb:'p_w_picpaths/6_b.jpg',title:'6.jpg'}]; $(function(){ $(".pic").children("img").each(function(){ var img = $(this); $(this).on("click",function(){ var thisImg = img.attr("src"); fotoramaImages(thisImg); }); }); }); function fotoramaImages(thisImg){ var data = []; var startindex = 0; //组装数据 if(p_w_picpaths){ for(var i=0;i<p_w_picpaths.length;i++){ var thumb = p_w_picpaths[i].thumb; var curImg = p_w_picpaths[i].url; var item = { img:curImg, thumb:thumb,full:curImg, id:i,caption:''}; data[i] = item; if(thumb == thisImg){ startindex = i; } } } //当前大图浏览到第几张(图片序号) var fotoramastartindex = parseInt(startindex); var fotorama = $('.fotorama').on('fotorama:show', function (e, fotorama) { //使用show回调函数显示图片总张数和当前第几张 var showIndex = (parseInt(fotorama.activeIndex)+1) +"/"+fotorama.size; var posDiv = $('#posDiv'); if(posDiv.length>0){ posDiv.empty().append(showIndex); }else{ $('.fotorama').append('<div id="posDiv">'+showIndex+'</div>') } }) .fotorama({startindex:fotoramastartindex,activeIndex:fotoramastartindex,data: data,allowfullscreen : true,nav:false}) .data('fotorama'); //初始化的activeIndex无用,不知道怎么回事,只能通过下面这个函数设置初始图片 fotorama.show({index:fotoramastartindex,time:20}); //点击即使用全屏浏览 fotorama.requestFullScreen(); //取消全屏即关闭大图 $('.fotorama').on('fotorama:fullscreenexit',function(e){ e.stopPropagation();//去掉事件冒泡 fotorama.destroy();//销毁组件 $('.fotorama').empty();//置空显示容器 }); } </script>
源代码见原文,原文转自:http://it.5yun.com.cn/html/y2015/m07/120.html