<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{
margin: 0;padding: 0;
}
div{
width: 60px;height: 60px;
background-color: #ff0;
position: absolute;
top: 100px;
left: 100px;
}
span{
width: 1px;
position: absolute;
height: 600px;
left: 800px;
background-color: #f00;
}
</style>
</head>
<body>
<div></div>
<span class="line">
</span>
<script>
var box = document.getElementsByTagName('div')[0];
//起点位置
var deltaX = 0;
//信号量
var nowX =100;
//移动的数组
var moveArr = [];
box.addEventListener('touchstart',function(event){
event.preventDefault();
//去掉过渡
box.style.transition = 'none';
//记录误差
deltaX = event.touches[0].clientX -deltaX-nowX;
},false)
box.addEventListener('touchmove',function(event){
event.preventDefault();
//改变信号量
nowX = event.touches[0].clientX-deltaX;
//移动
box.style.left = nowX+'px';
//记录手指位置
moveArr.push(event.touches[0].clientX);
},false)
box.addEventListener('touchend',function(event){
event.preventDefault();
//计算moveArr最后两个点之间的距离
var s =moveArr[moveArr.length -1]-moveArr[moveArr.length-2];
//s的大小决定了你的速度,计算一个新的有惯性的targetX
var targetX = nowX + s * 5;
console.log(nowX,s,targetX)
if (targetX >700) {
targetX = 700;
//使用贝塞尔曲线具有折返功能
box.style.transition='all 0.4s cubic-bezier(0.15,0.85,0.15,2.06) 0s';
}else if (targetX<0) {
targetX = 0;
box.style.transition='all 0.4s cubic-bezier(0.15,0.85,0.15,2.06) 0s';
}else{
box.style.transition='all 0.4s cubic-bezier(0.15,0.68,0,0.88) 0s';
}
box.style.left=targetX+'px';
//信号量改变成最终值
nowX = targetX;
},false)
</script>
</body>
</html>
惯性算法
最新推荐文章于 2022-11-06 23:08:21 发布