<!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">