移動端的慣性運動,最先來自 ios 的專利。用於手指滑動,離開屏幕以後,屏幕內容繼續滾動。更有動態感。javascript
這裏,以 pc 端,鼠標橫向(沿x軸) 拖拽的,慣性計算。移動端同理css
具體代碼以下:html
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>慣性運動</title> <style type="text/css"> #box{ background: pink; width: 100px; height: 100px; position: absolute; top: 100px; left: 100px; } </style> </head> <body> <div id="box"></div> </body> <script type="text/javascript"> var $box = document.getElementById("box"); var isDown = false; //是否按下鼠標 var inertance = 1.2; //慣性系數,越大,慣性越不明顯,不能小於0 var fv = 0; //滑動的力度 var timer = null; $box.onmousedown = function(e){ clearTimeout(timer);//清除定時器 fv = 0; this._start = e.clientX; //鼠標按下的位置 isDown = true;//鼠標是否有按下,主要防止用戶是從容器外開始滑動的 } $box.onmousemove = function(e){ if(isDown){ var miss = e.clientX - this._start; moveMiss(miss) this._start = e.clientX; fv = miss; } } function moveMiss(miss){ $box.style.left = miss + $box.offsetLeft + "px"; } window.onmouseup = function(e){ if(isDown){ isDown = false; var me = this; var friction = ((fv >> 31) * 2 + 1) * inertance;//根據力度套用公式計算出慣性大小,公式要記住 var num = Math.abs(friction); timer = setInterval(function(){ fv -= friction;//力度按 慣性的大小遞減 moveMiss(fv); if(Math.abs(fv) < num){ //若是力度減少到小於1了,結束,或者邊界彈回 clearInterval(timer); return ; } },20); } } </script> </html>