div在手机页面上随意拖动

效果

在这里插入图片描述

代码

代码很简单,里面也有注释。

<!doctype html>
<html>
<head>
    <title>手机拖动</title>
    <meta charset="utf-8">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
        }

        .barrage {
            position: fixed;
            display: block;
            top: 0;
        }

        .barrage_name {
            width: 100px;
            height: 100px;
            background: red;
            border-radius: 50%;
        }
    </style>
</head>

<body>
    <div class="barrage" id="barrage">
        <div class="barrage_name" id="barrage_name">
        </div>
    </div>
</body>
<script type="text/javascript">
    $(function () {
        var cont = $("#barrage");
        var contW = $("#barrage").width();
        var contH = $("#barrage").height();
        var startX, startY, sX, sY, moveX, moveY;
        var winW = $(window).width();
        var winH = $(window).height();

        cont.on({//绑定事件
            touchstart: function (e) {
                startX = e.originalEvent.targetTouches[0].pageX;    //获取点击点的X坐标    
                startY = e.originalEvent.targetTouches[0].pageY;    //获取点击点的Y坐标
                //console.log("startX="+startX+"************startY="+startY);
                sX = $(this).offset().left;//相对于当前窗口X轴的偏移量
                sY = $(this).offset().top;//相对于当前窗口Y轴的偏移量
                //console.log("sX="+sX+"***************sY="+sY);
                leftX = startX - sX;//鼠标所能移动的最左端是当前鼠标距div左边距的位置
                rightX = winW - contW + leftX;//鼠标所能移动的最右端是当前窗口距离减去鼠标距div最右端位置
                topY = startY - sY;//鼠标所能移动最上端是当前鼠标距div上边距的位置
                bottomY = winH - contH + topY;//鼠标所能移动最下端是当前窗口距离减去鼠标距div最下端位置                
            },
            touchmove: function (e) {
                e.preventDefault();
                moveX = e.originalEvent.targetTouches[0].pageX;//移动过程中X轴的坐标
                moveY = e.originalEvent.targetTouches[0].pageY;//移动过程中Y轴的坐标
                //console.log("moveX="+moveX+"************moveY="+moveY);
                if (moveX < leftX) { moveX = leftX; }
                if (moveX > rightX) { moveX = rightX; }
                if (moveY < topY) { moveY = topY; }
                if (moveY > bottomY) { moveY = bottomY; }
                $(this).css({
                    "left": moveX + sX - startX,
                    "top": moveY + sY - startY,
                })
            },
        })
    })
</script>
</html>

参考


作者:不敲代码的攻城狮
出处:https://www.cnblogs.com/leigq/
任何傻瓜都能写出计算机可以理解的代码。好的程序员能写出人能读懂的代码。

 
原文地址:https://www.cnblogs.com/leigq/p/13406550.html