下面代码只是实现了上下滑动惯性,没有写水平滑动惯性。(临时代码笔记,可能会在以后的过程中不断更新优化代码)
/** * 惯性原理: * 产生的速度 = 移动距离 / 移动时间 * 距离 = 松开的坐标 - 上次的坐标 (距离差) * 时间 = 松开的时间 - 按下的时间 (时间差) * */ var dargFun = { dargDom:null,//惯性滑动的DOM区域 startX:0,1)">开始偏移的X startY:0,1)">开始偏移的Y clientX:0,clientY:0保存的X偏移 translateY:0,1)">保存的Y偏移 maxWidth:0,1)">滑动的最大宽度 maxHeight:0,1)">滑动的最大高度 startTime:0,1)">记录初始按下时间 init:function(config){ this.dargDom = document.querySelector(config.dargDom); this.maxWidth = this.dargDom.offsetWidth; this.maxHeight = .dargDom.offsetHeight; this.dargDom.addEventListener('touchstart',(event)=>{ event.stopPropagation(); 停止事件传播 this.clientX = event.changedTouches[0].clientX; this.clientY = event.changedTouches[0].clientY; this.dargDom.style.WebkitTransition = this.dargDom.style.transition = ''; this.startX = .translateX; this.startY = .translateY; this.startTime = Date.now(); },false); this.dargDom.addEventListener('touchmove',1)">{ if(document.documentElement.scrollTop >= this.dargDom.scrollHeight - .dargDom.clientHeight){ }else{ return; } event.stopPropagation(); this.translateX = event.changedTouches[0].clientX - this.clientX + .startX; this.translateY = event.changedTouches[0].clientY - this.clientY + .startY; if(this.translateY > 0 ){ 拖动系数. 拉力的感觉 this.translateY *= 0.4; }else if( this.translateY < -(.dargDom.clientHeight)){ this.translateY = (event.changedTouches[0].clientY - this.clientY) * 0.4 + .startY; } this.animate(.translateY); },1)">this.dargDom.addEventListener('touchend',1)">var distanceY = event.changedTouches[0].clientY - .clientY,timeDis = Date.now() - this.startTime,1)">时间差 speed = (distanceY / timeDis) * 100; 惯性 this.translateY += speed; this.translateY = 0 添加贝塞尔曲线 this.dargDom.style.transition = 'transform 500ms cubic-bezier(0.1,0.57,0.1,1)'.translateY); },1)">); },animate:(y){ this.dargDom.style.WebkitTransform = this.dargDom.style.transform = 'translateY('+y+'px)'; } } export default dargFun;
调用方式:
dragFun.init({ dargDom:'#contractContanier' });
参考地址: