移动端悬浮div,单点触控

更新日期: 2020-03-08阅读: 1.9k标签: div

需求:

游戏内界面,增加悬浮球;默认展示位置为左上角.手指按住后可随手指在屏幕移动。松手后保持水平方向不变,根据松手时圆球所处的位置(处于屏幕左/右半部分),自动吸附到屏幕左侧/右侧(只需支持吸附到左侧/右侧,不用吸附到上下。刚好处于正中间则吸附到左侧);


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>适配移动端的拖动效果</title>
    <style>
        #div2{
            position: absolute;
            top:0;
            left:0;
            width: 100px;
            height: 100px;
            background: #bbbbbb;
        }
    </style>
</head>
<body>
    <div id="div2"></div>
<script>
    var flag = false;//鼠标|手指是否按下的标记
    var cur = {//记录鼠标|手指按下时的坐标
        x:0,
        y:0
    }
    var nx,ny,dx,dy,x,y ;
    var screenH = document.body.clientHeight;
    var screenW = document.body.clientWidth;
    //按下时的函数
    function down(){
        flag = true;//确认鼠标|手指按下
        var touch ;
        if(event.touches){
            touch = event.touches[0];//多个鼠标|手指事件取第一个
        }else {
            touch = event;
        }
        cur.x = touch.clientX; //记录鼠标|手指当前的x坐标
        cur.y = touch.clientY;//记录鼠标|手指当前的y坐标
        dx = div2.offsetLeft;//记录div当时的左偏移量
        dy = div2.offsetTop;//记录div的上偏移量
    }
    function move(){
        if(flag){//如果是鼠标|手指按下则继续执行
            var touch ;
            if(event.touches){
                touch = event.touches[0];
            }else {
                touch = event;
            }
            nx = touch.clientX - cur.x;//记录在鼠标|手指x轴移动的数据
            ny = touch.clientY - cur.y;//记录在鼠标|手指y轴移动的数据
            x = dx+nx; //div在x轴的偏移量加上鼠标|手指在x轴移动的距离
            y = dy+ny; //div在y轴的偏移量加上鼠标|手指在y轴移动的距离
            div2.style.left = x+"px";
            div2.style.top = y +"px";
            //阻止页面的滑动默认事件
            document.addEventListener("touchmove",function(){
                event.preventDefault();
            },false);
        }
    }
    //鼠标|手指释放时候的函数
    function end(){
        flag = false; //鼠标|手指释放
        if(x <= screenW/2){
            x = 0; //div在x轴的偏移量加上鼠标|手指在x轴移动的距离           
        }else{
            x = screenW;
        }
        y = dy+ny; //div在y轴的偏移量加上鼠标|手指在y轴移动的距离
        div2.style.left = x+"px";
        div2.style.top = y +"px";
    }
    var div2 = document.getElementById("div2");
    div2.addEventListener("mousedown",function(){
        down();
    },false);
    div2.addEventListener("touchstart",function(){
        down();
    },false)
    div2.addEventListener("mousemove",function(){
        move();
    },false);
    div2.addEventListener("touchmove",function(){
        move();
    },false)
    document.body.addEventListener("mouseup",function(){
        end();
    },false);
    div2.addEventListener("touchend",function(){
        end();
    },false);
</script>
</body>
</html>

链接: https://www.fly63.com/article/detial/9261

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!