- 如果没有viewport,页面上的东西会变得非常小
- 移动端由于点击事件是多点的,所以event中没有直接的clientX等等这些属性,而是放在了event.targetTouches里
- targetTouches和touches区别:后者有兼容问题
- touchmove这里,PC端把事件绑定到document上,移动端可以直接绑在点击的盒子上
- PC端,touchmove完了之后,即使松开鼠标盒子也会黏住鼠标,移动端虽然不会,但是这个事件依然存在,所以应该移除
- 匿名函数没法直接移除,所以应该把addEventListener中的函数放到外面
- touchend也要移除,留着没用,鼠标移动时还会添一个
代码:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title></title>
<style>
.box{width: 200px;height: 200px;background: #ccc;position: absolute;top: 0;left: 0;}
</style>
<script>
window.onload = function(){
let oBox = document.getElementsByClassName('box')[0]
oBox.addEventListener('touchstart',function(event){
let disX = event.targetTouches[0].clientX-oBox.offsetLeft
let disY = event.targetTouches[0].clientY-oBox.offsetTop
function fnMove(event){
oBox.style.left = event.targetTouches[0].clientX - disX + 'px'
oBox.style.top = event.targetTouches[0].clientY - disY + 'px'
}
function fnEnd(){
oBox.removeEventListener('touchmove',fnMove,false)
oBox.removeEventListener('touchend',fnEnd,false)
}
oBox.addEventListener('touchmove',fnMove,false)
oBox.addEventListener('touchend',fnEnd,false)
},false)
}
</script>
</head>
<body>
<div class="box">
</div>
</body>
</html>
效果: