首页 > 代码库 > js源生惯性滚动与回弹(备用)
js源生惯性滚动与回弹(备用)
js源生惯性滚动与回弹(备用)
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta name="Keywords" content="" /> <meta name="Description" content="" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta content="telephone=no" name="format-detection" /> <meta content="email=no" name="format-detection" /> <title>Document</title> <style> body{margin:0;padding:0;} div{position:relative;width:200px;height:300px;margin:3em auto;border:1px solid #CCC;overflow:hidden;-webkit-user-select:none;user-select:none;} ol{width:100%;} ol>li{height:30px;} </style> </head> <body> <div> <ol> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ol> </div> <script> function myScroll(ctx){ var ol=ctx.firstElementChild||ctx.firstChild, offset=50, cur=0, isDown=false, vy=0, isInTransition=false; ctx.addEventListener("mousedown",function(e){ if(isInTransition)return; clearTimeout(this._timer); vy=0; this._oy=e.clientY-cur; this._cy=e.clientY; this._oh=this.scrollHeight; this._ch=this.clientHeight; this._startTime=e.timeStamp; isDown=true; }); ctx.addEventListener("mousemove",function(e){ if(isDown) { if(e.timeStamp-this._startTime>40) { this._startTime=e.timeStamp; cur=e.clientY-this._oy; if(cur>0) { cur*=0.4; } else if(cur<this._ch-this._oh) { cur=(cur+this._oh-this._ch)*0.4-this._oh+this._ch; } setPos(cur); } vy=e.clientY-this._cy; this._cy=e.clientY; } },false); ctx.addEventListener("mouseleave",mleave,false); ctx.addEventListener("mouseup",mleave,false); function setPos(y){ ol.style.transform="translateY("+y+"px) translateZ(0)"; } function ease(target){ isInTransition=true; ctx._timer=setInterval(function(){ cur-=(cur-target)*0.2; if(Math.abs(cur-target)<1) { cur=target; clearInterval(ctx._timer); isInTransition=false; } setPos(cur); },20); } function mleave(e){ if(isDown) { isDown=false; var t=this,friction=((vy>>31)*2+1)*0.5,oh=this.scrollHeight-this.clientHeight; this._timer=setInterval(function(){ vy-=friction; cur+=vy; setPos(cur); if(-cur-oh>offset) { clearTimeout(t._timer); ease(-oh); return; } if(cur>offset) { clearTimeout(t._timer); ease(0); return; } if(Math.abs(vy)<1) { clearTimeout(t._timer); if(cur>0) { ease(0); return; } if(-cur>oh) { ease(-oh); return; } } },20); } } } myScroll(document.querySelector("div")); </script> </body></html>
js源生惯性滚动与回弹(备用)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。