在webapp中,会遇到在一个容器中显示多个图片,然后可以左右滑动的情况,于是基于jquery写了一个,智能手机上可以看到效果
预览地址:http://kardel.sinaapp.com/qqbuy/sy.html
1 $.fn.scrollImage = function (option) { 2 var setting = { 3 // 显示出来的图片数量 4 showNum:3, 5 // 滑动效果的速度 6 speed:300, 7 // 图片间的间隙 8 gapWidth:1 9 }; 10 if (option) { 11 $.extend(setting, option); 12 } 13 var ulNode = $(this); 14 ulNode.each(function () { 15 var node = $(this); 16 doScrollImage(node); 17 }); 18 function doScrollImage(node) { 19 var childList = node.children(); 20 // 子节点个数 21 var counts = childList.length; 22 // 单个元素的宽度 23 var li_width = childList.width() + setting.gapWidth; 24 var ulNodeWidth = li_width * counts; 25 // 初始化节点的样式信息 26 node.css({"width":ulNodeWidth, "left":0}); 27 node[0].ontouchstart = handleTouchStart; 28 function handleTouchStart(e) { 29 var touch = e.targetTouches[0]; 30 var startX = touch.pageX; 31 var startY = touch.pageY; 32 // 手指放下时的left值 33 var currentPosition = node.css("left"); 34 node[0].ontouchmove = handleTouchMove; 35 function handleTouchMove(moveEvent) { 36 var moveTouch = moveEvent.targetTouches[0]; 37 var moveX = moveTouch.pageX; 38 var moveY = moveTouch.pageY; 39 var x = moveX - startX , y = moveY - startY; 40 if (Math.abs(x) - Math.abs(y) > 10) { 41 // 阻止默认的事件 42 moveEvent.preventDefault(); 43 node.css("left", parseInt(currentPosition, 10) + x); 44 } 45 // 判断滑动方向 46 var direct = x > 0 ? "sub" : "add"; 47 node[0].ontouchend = handleTouchEnd; 48 function handleTouchEnd() { 49 // 手放开时节点的left值 50 var leftValue = parseInt(node.css("left"), 10); 51 if (leftValue > 0) { 52 // 右滑动距离小于0,返回到0 53 node.animate({left:0}, setting.speed); 54 } else { 55 leftValue = Math.abs(leftValue); 56 var dif = ulNodeWidth - leftValue; 57 if (dif < li_width * setting.showNum) { 58 node.animate({left:-(ulNodeWidth - li_width * setting.showNum)}, setting.speed); 59 } else { 60 var all = leftValue + li_width * setting.showNum; 61 // 计算滑过的图片的张数,不足一张的需要补全一张的宽度 62 if (all % li_width != 0) { 63 // 左滑动向上取整,右滑动向下取整 64 var scrollCount = direct == "add" ? Math.ceil(all / li_width) : Math.floor(all / li_width); 65 node.animate({left:-(scrollCount - setting.showNum) * li_width}, setting.speed); 66 } 67 } 68 } 69 node[0].ontouchmove = null; 70 node[0].ontouchend = null; 71 } 72 } 73 } 74 } 75 }
关注前端 关注web app 关注性能