移动端拖拽-Document
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" /> <meta name="keywords" content=""> <meta name="description" content=""> <meta name="format-detection" content="telephone=no" /> <title>移动端拖拽-Document</title> <style type="text/css"> body { position: relative; width: 100vw; height: 100vh; margin: 0; padding: 0; background-color: #1cee89; } div { position: absolute; left: 40px; top: 40px; width: 100px; height: 100px; background-color: #8294ff; border-radius: 20px; cursor: move; user-select: none; } </style> </head> <body> <div></div> <script type="text/javascript" charset="utf-8"> const body = document.querySelector('body'); const div = document.querySelector('div'); // 获得盒子最大移动位置 const maxLeft = body.offsetWidth - div.offsetWidth; const maxTop = body.offsetHeight - div.offsetHeight; // 获取手指初始坐标 var startX = 0; var startY = 0; // 获得盒子原来的位置 var x = 0; var y = 0; // 手指触摸 div.addEventListener('touchstart', function(e) { // 获取手指初始坐标 startX = e.targetTouches[0].pageX; startY = e.targetTouches[0].pageY; x = this.offsetLeft; y = this.offsetTop; this.style.boxShadow = '0 0 15px rgba(0, 0, 0, .6)'; }); // 手指离开 div.addEventListener('touchend', function(e) { this.style.boxShadow = ''; }); // 手指按住移动 div.addEventListener('touchmove', function(e) { // 计算手指的移动距离:手指移动之后的坐标减去手指初始的坐标 let moveX = e.targetTouches[0].pageX - startX; let moveY = e.targetTouches[0].pageY - startY; let lastLeft = x + moveX; let lastTop = y + moveY; //防止超出父元素范围 if (lastLeft < 0) lastLeft = 0; if (lastTop < 0) lastTop = 0; if (lastLeft > maxLeft) lastLeft = maxLeft; if (lastTop > maxTop) lastTop = maxTop; // 移动盒子 盒子原来的位置 + 手指移动的距离 this.style.left = lastLeft + 'px'; this.style.top = lastTop + 'px'; // 控制台 打印位置 console.log(lastLeft + 'px'); console.log(lastTop + 'px'); // 阻止屏幕滚动的默认行为 e.preventDefault(); }); </script> </body> </html>