移動端視窗
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
說明
width=device-width 應用程序的寬度和屏幕的寬度是一樣的
initial-scale=1.0 應用程序啟動時候的縮放尺度(1.0表示不縮放)
user-scalable=no/0 //用戶是否可以通過他的手勢來縮放整個應用程序,使應用程序的尺度發生一個改變 (no 和 0 一個理解 )
移動端的事件綁定
移動端的事件綁定是通過 ** addEventListener ** 添加
移動端的事件
touchstart: 開始觸屏事件 (于手指點擊屏幕開始,觸屏事件將會有300ms的延遲,因為這樣可以判定它是否有第二次點擊)
touchmove: 移動事件 (手指在屏幕移動,在這里可以判斷移動)
touchend : 結束事件 (手指離開屏幕,結束可以判定與touchstart開始的距離)
touchcancel : 中止事件 (在手機中,接聽電話的優先級最高,所以在手機在進行其他操作時,就需要用到該屬性)
那么這些屬性我們需要從哪里獲取呢?
我們可以在事件中傳參e來看看
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>測試</title>
<style>
.div1{
height: 300px;
width: 300px;
background-color: red;
}
</style>
</head>
<body>
<div class="div1"></div>
<script>
var div1 = document.querySelector(".div1");
// 綁定開始觸摸事件
div1.addEventListener('touchstart',function(e){
console.log(e);
})
</script>
測試.jpg
其中我們可以看見changeTouches和targetTouches屬性,那么就可見看看其中的值:
changedtouches.jpg
targettouches.jpg
在其中我們可以看見點擊時的位置以及離開時的距離,其中targetTouches為開始點擊屏幕的屬性,而changedTouches為離開屏幕的屬性,那么我們就可以進行一些最基本的操作,例如:div的移動
<!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, user-scalable=0">
<title>拖拽</title>
<style>
.div1{
height: 200px;
width: 200px;
background-color: green;
position: absolute;
}
</style>
</head>
<body>
<div class="div1"></div>
<script>
var div = document.querySelector(".div1");
div.addEventListener('touchstart',function(e){
var left = e.targetTouches[0].pageX - this.offsetLeft;
var top = e.targetTouches[0].pageY - this.offsetTop;
div.addEventListener('touchmove',function(e){
var touches = e.targetTouches;
var touch = touches[0];
this.style.left = touch.pageX - left + 'px';
this.style.top = touch.pageY - top + 'px';
})
})
</script>
</body>
</html>