layui 手机端轮播图实现触屏滑动轮播
html代码:
<div class="layui-carousel" id="test1"> <div carousel-item> <div class="layui-row"> <img src="image/lunbo5.png"> </div> <div class="layui-row"> <img src="image/lunbo1.png"> </div> </div> </div>
js代码:因需要,只需要左右滑动,上下释放给浏览器默认操作。
layui.use(['carousel','element','layer','jquery'], function(){ var carousel = layui.carousel, $ = layui.jquery, layer = layui.layer, element = layui.element; //导航的hover效果、二级菜单等功能,需要依赖element模块 //渲染轮播图及处理轮播图高度 var W = $('#test1').width();//获取容器的宽度 var screenImage = $('#test1 img');//获取轮播图DOM var theImage = new Image(); theImage.src = screenImage.attr("src"); var b = theImage.width/theImage.height;//获取轮播图的原始宽高比例 var ins = carousel.render({ elem: '#test1' ,width: '100%' //设置容器宽度 ,height: parseFloat((W/b).toString())+60+"px" ,arrow: is_Pc() ? 'hover':'none' //箭头 ,anim: 'fade' //切换动画方式 ,indicator:'none' }); //移动端手指滑动轮播图 $("#test1").on("touchstart", function (e) { var startX = e.originalEvent.targetTouches[0].pageX;//开始坐标X var startY = e.originalEvent.targetTouches[0].pageY;//结束坐标Y $(this).on('touchmove', function (e) { var silde = doSlide(startX,startY,e); silde == 'left' || silde == 'right' ? arguments[0].preventDefault() : ''; }); $(this).on('touchend', function (e) { var silde = doSlide(startX,startY,e); if(silde == 'left'){ ins.slide("add"); $(this).off('touchmove touchend'); }else if(silde == 'right'){ ins.slide("sub"); $(this).off('touchmove touchend'); } }); }) //判断滑动的方向 function doSlide(startX,startY,e){ var endX = e.originalEvent.changedTouches[0].pageX;//结束坐标X var endY = e.originalEvent.changedTouches[0].pageY;//结束坐标X var X = endX - startX,Y = endY - startY; if( Math.abs(X) > Math.abs(Y) && X > 0 ){ return 'right'; }else if ( Math.abs(X) > Math.abs(Y) && X < 0 ){ return 'left'; }else if ( Math.abs(Y) > Math.abs(X) && Y > 0){ return 'bottom'; }else if ( Math.abs(Y) > Math.abs(X) && Y < 0 ){ return 'top'; }else{ return 'just'; } } });