拖拽效果实现方法
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
ul{
list-style:none;
}
#box{
width:100px;
height:100px;
background:darkred;
color:white;
position: absolute;
left:0;
top:0;
}
</style>
</head>
<body>
<div id="box">
</div>
<script>
var box = document.querySelector('#box');
box.addEventListener('touchstart',function(e){
// 获取 按下时触点的位置 尺寸1
this.size1 = e.touches[0].clientX;
// 盒子距离左边的位置
this.size2 = box.offsetLeft;
this.size1Y = e.touches[0].clientY;
this.size2Y = box.offsetTop;
})
box.addEventListener('touchmove',function(e){
// 手指离开的 触点的位置
this.size3 = e.touches[0].clientX;
this.size3Y = e.touches[0].clientY;
this.size4 = this.size3 - (this.size1 - this.size2)
this.size4Y = this.size3Y - (this.size1Y - this.size2Y)
// 获取最大 left 值
var maxLeft = document.documentElement.clientWidth - box.offsetWidth;
// 检测水平方向值
if(this.size4 <= 0 ){
this.size4 = 0;
}
if(this.size4 > maxLeft ){
this.size4 = maxLeft;
}
// 设置 css 的 left 的值
this.style.left = this.size4+ 'px';
this.style.top = this.size4Y < 0 ? 0 : this.size4Y + 'px';
})
box.addEventListener('touchend',function(){
})
document.documentElement.addEventListener('touchstart',function(e){
e.preventDefault();
},{
passive:false
})
</script>
</body>
</html>
我是Eric,手机号是13522679763

浙公网安备 33010602011771号