下面代碼只是實現了上下滑動慣性,沒有寫水平滑動慣性。(臨時代碼筆記,可能會在以后的過程中不斷更新優化代碼)
/** * 慣性原理: * 產生的速度 = 移動距離 / 移動時間 * 距離 = 松開的坐標 - 上次的坐標 (距離差) * 時間 = 松開的時間 - 按下的時間 (時間差) * */ var dargFun = { dargDom:null, //慣性滑動的DOM區域 startX:0, //開始偏移的X startY:0, //開始偏移的Y clientX:0, clientY:0, translateX:0, //保存的X偏移 translateY:0, //保存的Y偏移 maxWidth:0, //滑動的最大寬度 maxHeight:0, //滑動的最大高度 startTime:0, //記錄初始按下時間 init:function(config){ this.dargDom = document.querySelector(config.dargDom); this.maxWidth = this.dargDom.offsetWidth; this.maxHeight = this.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 = this.translateX; this.startY = this.translateY; this.startTime = Date.now(); },false); this.dargDom.addEventListener('touchmove',(event)=>{ if(document.documentElement.scrollTop >= this.dargDom.scrollHeight - this.dargDom.clientHeight){ }else{ return; } event.stopPropagation(); //停止事件傳播 this.translateX = event.changedTouches[0].clientX - this.clientX + this.startX; this.translateY = event.changedTouches[0].clientY - this.clientY + this.startY; if(this.translateY > 0 ){ //拖動系數. 拉力的感覺 this.translateY *= 0.4; }else if( this.translateY < -(this.dargDom.scrollHeight - this.dargDom.clientHeight)){ this.translateY = (event.changedTouches[0].clientY - this.clientY) * 0.4 + this.startY; } this.animate(this.translateY); },false); this.dargDom.addEventListener('touchend',(event)=>{ event.stopPropagation(); //停止事件傳播 var distanceY = event.changedTouches[0].clientY - this.clientY, timeDis = Date.now() - this.startTime, //時間差 speed = (distanceY / timeDis) * 100; // 慣性 this.translateY += speed; this.translateY = 0; // 添加貝塞爾曲線 this.dargDom.style.WebkitTransition = this.dargDom.style.transition = 'transform 500ms cubic-bezier(0.1, 0.57, 0.1, 1)'; this.animate(this.translateY); },false); }, animate:function(y){ this.dargDom.style.WebkitTransform = this.dargDom.style.transform = 'translateY('+y+'px)'; } } export default dargFun;
注:當滑動到頁面底部的時候才觸發touchmove事件。
調用方式:
dragFun.init({ dargDom:'#contractContanier' });
參考地址:
