MUI拖拽div盒子,不能拖拽出视口

<!doctype html> <!-- 文档类型声明,指定使用 HTML5 -->
<html lang="en"> <!-- HTML 根元素,语言设置为英语 -->
<head>
    <meta charset="UTF-8" /> <!-- 字符编码声明,使用 UTF-8 编码 -->
    <title>Document</title> <!-- 页面标题 -->
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <!-- 视口设置,确保页面在不同设备上正确显示 -->
    <link rel="stylesheet" type="text/css" href="./css/mui.css" /> <!-- 引入外部 CSS 文件,用于页面样式 -->
</head>
<style>
    .box1 {
        width: 200px; /* 设置元素的宽度为 200px */
        height: 200px; /* 设置元素的高度为 200px */
        background-color: blue; /* 设置元素的背景颜色为蓝色 */
        position: absolute; /* 设置元素的定位方式为绝对定位 */
    }
</style>
<body>
    <div class="box1"></div> <!-- 创建一个 div 元素,并应用 .box1 类 -->
    <script src="./js/mui.js" type="text/javascript" charset="utf-8"></script> <!-- 引入外部 JavaScript 文件,包含 mui 库 -->
    <script type="text/javascript">
        mui.init({
            gestureConfig: {
                tap: true, // 允许点击手势
                doubletap: true, // 允许双击手势
                longtap: true, // 允许长按手势
                swipe: true, // 允许滑动手势
                drag: true, // 允许拖拽手势
                hold: false, // 不允许按住手势
                release: false // 不允许释放手势
            }
        });
        var box1 = document.querySelector('.box1'); // 获取页面中具有 .box1 类的元素
        var ix = 0, iy = 0; // 初始化触摸起始位置的坐标
        var cx = 0, cy = 0; // 初始化元素的当前位置坐标
        let _h = window.innerHeight - box1.offsetHeight; // 计算元素可移动的最大高度
        let _w = window.innerWidth - box1.offsetWidth; // 计算元素可移动的最大宽度
        box1.addEventListener('touchstart', (e) => { // 为元素添加触摸开始事件监听器
            e.preventDefault(); // 阻止默认事件
            ix = e.touches[0].clientX - cx; // 计算触摸点相对于元素起始位置的 X 坐标
            iy = e.touches[0].clientY - cy; // 计算触摸点相对于元素起始位置的 Y 坐标
        }, false);
        box1.addEventListener('touchmove', (e) => { // 为元素添加触摸移动事件监听器
            e.preventDefault(); // 阻止默认事件
            cx = e.touches[0].clientX - ix; // 更新元素的 X 坐标
            cy = e.touches[0].clientY - iy; // 更新元素的 Y 坐标
            cy = Math.min(Math.max(0, cy), _h); // 限制元素的 Y 坐标在可移动范围内
            cx = Math.min(Math.max(0, cx), _w); // 限制元素的 X 坐标在可移动范围内
            box1.style.top = cy + 'px'; // 设置元素的顶部位置
            box1.style.left = cx + 'px'; // 设置元素的左侧位置
        }, false);
    </script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值