JavaScript拖拽

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div {
            top: 0;
            left: 0;
            width: 120px;
            height: 120px;
            position: absolute;
            background-color: aqua;
        }
    </style>
</head>

<body>
    <div></div>
</body>

</html>
<script>
    
    let div = document.getElementsByTagName('div')[0] // 获取div标签

    let flag = false // 判断是否进行拖拽的状态

    let pagex = 0 // 点击时获取鼠标相对于document的left距离

    let pagey = 0 // 点击时获取鼠标相对于document的top距离

    let x = 0  //用来存储盒子的left距离

    let y = 0  //用来存储盒子的top距离

    // 手指按下时触发 -- ontouchstart
    div.ontouchstart = function (e) {
        // 按下可以进行拖拽
        flag = true
        // 鼠标在document的位置 减去 盒子 距离左边的位置
        // 求出鼠标在盒子里的left的距离
        pagex = e.touches[0].pageX - x
        // 鼠标在document的位置 减去 盒子 距离上边的位置
        // 求出鼠标在盒子里的top的距离
        pagey = e.touches[0].pageY - y
    }

    // 手指移动时触发 -- ontouchmove
    div.ontouchmove = function (e) {
        // flag为true可以进行拖拽
        if (flag) {
            // e.touches[0].pageX - pagex , e.touches[0].pageY - pagey
            // 鼠标在document的 left、top 减去 鼠标在盒子里的 left、top
            // 求出移动时盒子的新的 left、top 距离

            // 全局变量x记录 移动时 盒子里距离x轴的距离
            // 全局变量y记录 移动时 盒子里距离y轴的距离
            x = e.touches[0].pageX - pagex
            y = e.touches[0].pageY - pagey
            // 让div的 lfet 值 等于 移动时 盒子里距离x轴的距离 
            // 让div的 top 值 等于 移动时 盒子里距离y轴的距离 
            div.style.left = e.touches[0].pageX - pagex + 'px'
            div.style.top = e.touches[0].pageY - pagey + 'px'
        }
    }

    // 手指离开时触发 -- ontouchend
    div.ontouchend = function (e) {
        // 手指离开取消拖拽
        flag = false
    }
</script>

移动端的代码,如果想用PC端的话更改 

<!--<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"> -->
<meta name="viewport" content="width=device-width,initial-scale=1.0">

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值