touch拖拽 惯性滑动

昨晚闲来无事,写的滑动惯性,js水平一般,求各位大神指点
<style>
html,body{
padding: 0;
margin: 0;
}
.box{
width: 50px;
height: 50px;
background: red;
position: absolute;
top: 100px;
left: 100px;
}
</style>

html:
<div class="box"></div>

<script>
var box = $('.box');
var t = null;
var clientX = 0,
left = box.offsetLeft,
chuX = 0,
clientY = 0,
tops = box.offsetTop,
chuY = 0,
time1 = 0,
box.ontouchstart=function(e){
var juLi = e.changedTouches[0];
clientX = juLi.clientX;
clientY = juLi.clientY;
chuX = clientX;
chuY = clientY;
time1 = e.timeStamp;
box.ontouchmove=function(e){
var juLi = e.changedTouches[0];
left = juLi.clientX - clientX + left;
tops = juLi.clientY - clientY + tops;
clientX = juLi.clientX;
clientY = juLi.clientY;
box.style.left = left + 'px';
box.style.top = tops + 'px';
}
document.ontouchend=function(e){
var juLi = e.changedTouches[0];
var speedX = juLi.clientX - chuX;
var speedY = juLi.clientY - chuY;
var time = e.timeStamp - time1;//时间差
//取消touchmove和touchend事件
box.onontouchmove = null;
document.ontouchend = null;
move(box,speedX,speedY,time)
}
}
//惯性函数
function move(obj,speedX,speedY,time){
clearInterval(t);
//计算x,y的移动速度
speedX = speedX30/time;
speedY = speedY
30/time;
t = setInterval(function(){
speedX *= 0.95 //摩擦
speedY *= 0.95 //摩擦
var x = left+speedX;
var y = tops+speedY;
if(x <= 0){
x=0;
}
if(x >= width){
x = width
}
if(y <=0){
y = 0;
}
if(y >= height){
y = height
}
obj.style.left = x +'px';
obj.style.top = y +'px';
left = left+speedX;
tops = tops+speedY;
if(Math.abs(speedX) < 1 && Math.abs(speedY) < 1){
speedX = 0;
speedY = 0;
}
// if(Math.abs(speedY) < 1){
// speedY = 0
// };
if((speedX == 0 && speedY == 0) || (y == height && x == width)){
clearInterval(t);
}
},30);
}

function $(obj){
return document.querySelector(obj)
}
</script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 日更第23篇又到了一年一度揩油做年目标的时候了,我15年底的时候报名了小组互助通道。报名前,我咨询了Panda,他...
    羽青阅读 2,507评论 0 0
  • 关于电影 一月观影记录:《I型起源》、《消失的爱人》、《少数派报告》、《智取威虎山》、《黄金时代》、《盗梦空间》 ...
    戒嗔阅读 2,532评论 0 1
  • 是一钩银月压弯了夜的脊梁 是夜的浓雾红了我眼眶 我在千里之外的家乡 默默数你的白发 三千丈 路, 还有多长? 还是...
    肾毒阅读 1,859评论 35 25
  • 时间:2015.11.12 16:30-17:10进度:第二十六章 iMac "你好(又见面了)"书摘: 总结:重...
    MissBao88阅读 2,118评论 0 0
  • 活在尴尬的年华里,不是富二代,不是星二代,是的,出了自己奋斗你还能选择什么?从来没有觉得这样有什么不好,总是很认真...
    Crystal_Z阅读 1,423评论 0 0

友情链接更多精彩内容