js代碼
$(function() { function judge() { var startx;//讓startx在touch事件函數里是全局性變量。 var endx; var el = document.getElementById('io');//觸摸區域。 function cons() { //獨立封裝這個事件可以保證執行順序,從而能夠訪問得到應該訪問的數據。 if (startx > endx) { //判斷左右移動程序 alert("left"); } else { alert("right"); } } el.addEventListener('touchstart', function (e) { var touch = e.changedTouches; startx = touch[0].clientX; starty = touch[0].clientY; }); el.addEventListener('touchend', function (e) { var touch = e.changedTouches; endx = touch[0].clientX; endy = touch[0].clientY; cons(); //startx endx 的數據收集應該放在touchend事件后執行,而不是放在touchstart事件里執行,這樣才能訪問到touchstart和touchend這2個事件產生的startx和endx數據。另外startx和endx在_touch事件函數里是全局性的,所以在此函數中都可以訪問得到,所以只需要注意事件執行的先后順序即可。 }); } judge(); })
html隨便寫就可以 記得id要對應
<body> <div style="width: 100%;height: 3000px;background: #08c;" id="io"> </div> </body>