代码改变世界

javascript 的惯性运动

2019-05-09 14:36  muamaker  阅读(1063)  评论(0编辑  收藏  举报

移动端的惯性运动,最早来自 ios 的专利。用于手指滑动,离开屏幕之后,屏幕内容继续滚动。更有动态感。

 

这里,以 pc 端,鼠标横向(沿x轴) 拖拽的,惯性计算。移动端同理

 

具体代码如下:

<!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>