<!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, initial-scale=1.0">
<meta name='viewport' content='width=device-width, initial-scale=1.0,minmum-scale=1,maxmum-scale=1,user-scalable=no'>
<title>Document</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: red;
border-radius: 50%;
position: absolute;
transform: translate(0,0);
}
</style>
</head>
<body>
<div class="box">
</div>
</body>
<script>
let obox=document.querySelector('.box')
// 获取光标距离盒子左边得距离
// touches手指点击事件对象
// getBoundingClientRect获取transform移动值,别的获取不到
let CursorBoxDistanceleft;
let CursorBoxDistancetop
obox.ontouchstart=function(e){
// 获取光标在盒子左边的距离
CursorBoxDistance= e.touches[0].pageX - obox.getBoundingClientRect().left
// 获取鼠标距离盒子上方得距离
CursorBoxDistancetop=e.touches[0].pageY - obox.getBoundingClientRect().top
move(CursorBoxDistance,CursorBoxDistancetop)
}
function move(CursorBoxDistance,CursorBoxDistancetop){
obox.ontouchmove=function(ev){
// 拿光标左边位置减去光标距离盒子的左边值得到的就是盒子,X移动的值,Y也是一样的
let setValueX=Math.floor(ev.touches[0].pageX - CursorBoxDistance)
let setValueY=Math.floor(ev.touches[0].pageY - CursorBoxDistancetop)
// 最后设置盒子的值
obox.style.transform=`translate(${setValueX}px,${setValueY}px)`
}
}
// 个人账号qq,2697018256
</script>
</html>
移动端,利用transform,实现div拖拽,看完不会你打我
最新推荐文章于 2023-05-17 09:37:16 发布
关键词由CSDN通过智能技术生成