//滑动函数 function SlideHorizontal(id ){ this.id = id; this.startX = 0; this.moveX = 0; this.endX = 0; this.startMarginLeft = 0; this.speed = 0; this.moveHappen = false; this.vertical = 0; this.mouseStart = false; var scope = this; $("#" + this.id).on("touchstart",function(e){ scope.mouseStart = true; touchStartFn(e); }); $("#" + this.id).on("mousedown",function(e){ scope.mouseStart = true; touchStartFn(e); }); $("#" + this.id).on("touchmove",function(e){ touchMoveFn(e); }); $("#" + this.id).on("mousemove",function(e){ touchMoveFn(e); }); $("#" + this.id).on("touchend",function(e){ scope.mouseStart = false; touchEndFn(e); }); $("#" + this.id).on("mouseup",function(e){ scope.mouseStart = false; touchEndFn(e); }); function touchStartFn(e){ if (e.clientX) { scope.moveX = scope.startX = e.clientX; scope.startY = e.clientY; }else{ var touch = e.originalEvent.changedTouches[0]; scope.moveX = scope.startX = touch.clientX; scope.startY = touch.clientY; } scope.moveHappen = false; scope.startMarginLeft = parseFloat($("#" + scope.id).css("marginLeft")); } function touchMoveFn(e){ if (scope.mouseStart) { if (e.clientX) { scope.speed = e.clientX - scope.moveX; scope.moveX = e.clientX; scope.speedY = e.clientY - scope.startY; }else{ var touch = e.originalEvent.changedTouches[0]; scope.speed = touch.clientX - scope.moveX; scope.moveX = touch.clientX; scope.speedY = touch.clientY - scope.startY; } if (scope.vertical !== 2 && scope.vertical !== 1) { if (Math.abs(scope.speedY) > Math.abs(scope.speed)) { scope.vertical = 1; }else{ scope.vertical = 2; scope.moveHappen = true; } } if (scope.vertical === 2) { e.preventDefault(); var dx = scope.moveX - scope.startX; var marginLeft = scope.startMarginLeft + dx; if (marginLeft > 50) { marginLeft = 50; } if (marginLeft < -moreLength - 50) { marginLeft = -moreLength - 50; } $("#" + scope.id).css({ "margin-left" : marginLeft }); scope.time1 = (new Date()).getTime(); } } } function touchEndFn(e){ if (e.clientX) { scope.endX = e.clientX; }else{ var touch = e.originalEvent.changedTouches[0]; scope.endX = touch.clientX; } scope.time2 = (new Date()).getTime(); if (scope.time2 - scope.time1 > 20) { scope.speed = 0; } //console.log(scope.time2 - scope.time1); var marginLeft = parseFloat($("#" + scope.id).css("margin-left")) + scope.speed*20; if (scope.moveHappen && scope.vertical === 2) { if (marginLeft > 0) { $("#" + scope.id).animate({ "margin-left" : 0 },200,"linear"); }else if (marginLeft < -moreLength) { $("#" + scope.id).animate({ "margin-left" : -moreLength },200,"linear"); }else{ $("#" + scope.id).animate({ "margin-left" : marginLeft },200,"linear"); } } scope.vertical = 0; } }; new SlideHorizontal("goodsUl");