- 如果沒有viewport,頁面上的東西會(huì)變得非常小
- 移動(dòng)端由于點(diǎn)擊事件是多點(diǎn)的,所以event中沒有直接的clientX等等這些屬性,而是放在了event.targetTouches里
- targetTouches和touches區(qū)別:后者有兼容問題
- touchmove這里,PC端把事件綁定到document上,移動(dòng)端可以直接綁在點(diǎn)擊的盒子上
- PC端,touchmove完了之后,即使松開鼠標(biāo)盒子也會(huì)黏住鼠標(biāo),移動(dòng)端雖然不會(huì),但是這個(gè)事件依然存在,所以應(yīng)該移除
- 匿名函數(shù)沒法直接移除,所以應(yīng)該把a(bǔ)ddEventListener中的函數(shù)放到外面
- touchend也要移除,留著沒用,鼠標(biāo)移動(dòng)時(shí)還會(huì)添一個(gè)
代碼:
<!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>
效果:
