用手拖动ul,可以根据速度,惯性移动不同距离,超出范围了还能回弹,供参考~
//得到各种元素
var nav = document.querySelector("nav");
var navul = document.querySelector("nav ul");
var navullis = document.querySelectorAll("nav ul li");
var navW = parseInt(window.getComputedStyle(nav , null)['width']);
//宽度
navul.style.width = navullis.length * 82 +"px";
nav.addEventListener("touchstart",touchstartHandler);
nav.addEventListener("touchmove",touchmoveHandler);
nav.addEventListener("touchend",touchendHandler);
var startX;
var nowX = 0;
var dX;
var lastTwoPoint = [0,0];
//开始滑动
function touchstartHandler(event){
navul.style.webkitTransition = "none"; //去掉过渡
navul.style.transition = "none"; //去掉过渡
startX = event.touches[0].pageX; //记录起点
}
//滑动过程
function touchmoveHandler(event){
event.preventDefault();
dX = event.touches[0].pageX - startX; //差值
//反映差值
navul.style.webkitTransform = "translateX(" + (nowX + dX) + "px)";
navul.style.transform = "translateX(" + (nowX + dX) + "px)";
//记录最后两点的x值
lastTwoPoint.shift();
lastTwoPoint.push(event.touches[0].pageX);
}
//结束滑动
function touchendHandler(event){
nowX += dX;
//多走最后两点路程的5倍路程
nowX += (lastTwoPoint[1] - lastTwoPoint[0]) * 5;
if(nowX > 0){
nowX = 0;
}
if(nowX < -parseInt(navul.style.width) + navW){
nowX = -parseInt(navul.style.width) + navW;
}
console.log(-parseInt(navul.style.width) + navW)
//过渡时间
//非线性衰减
var t = Math.sqrt(Math.abs(lastTwoPoint[1] - lastTwoPoint[0])) / 10;
navul.style.webkitTransition = "all " + t + "s cubic-bezier(0.1, 0.85, 0.25, 1) 0s";
navul.style.transition = "all " + t + "s cubic-bezier(0.1, 0.85, 0.25, 1) 0s";
//反映多走的5倍路程:
navul.style.webkitTransform = "translateX(" + nowX + "px)";
navul.style.transform = "translateX(" + nowX + "px)";
}