美文网首页
touch拖拽 惯性滑动

touch拖拽 惯性滑动

作者: 月光_薛 | 来源:发表于2018-08-07 09:05 被阅读0次

    昨晚闲来无事,写的滑动惯性,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>

    相关文章

      网友评论

          本文标题:touch拖拽 惯性滑动

          本文链接:https://www.haomeiwen.com/subject/etqovftx.html