前面寫過1篇 jquery mobile.js的swipe事件,來實現開關按鈕的效果。查看資料后發現,swipe事件左右事件,移動端的上下滑動事件並不是用swipe.
網上搜索之后,發現移動端的原生事件touch可以解決這個問題。touch事件
本文例子的要求是:上下滑動超過給定的像素,隱藏/顯示頁面的元素。開始是隱藏的狀態。
注意,touch事件並需要引入任何的js庫。
<!DOCTYPE html> <html id="a"> <head lang="en"> <meta charset="UTF-8"> <title>1元許願</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <meta name="apple-mobile-web-app-capable" content="no"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="format-detection" content="telephone=no"> <style> .div1{width:200px;height:200px;background:#F00;} </style> </head> <body class="bg-home"> <div class="div1"> </div> <section class="padding-bottom-80" data-tag="css-nav"> </section> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script> $('.div1').bind('click',function(){ alert('a'); }) </script> <script> //touch事件相關的的代碼 var startX, startY, endX, endY; document.getElementById("a").addEventListener("touchstart", touchStart, false); document.getElementById("a").addEventListener("touchmove", touchMove, false); document.getElementById("a").addEventListener("touchend", touchEnd, false); function touchStart(event) { var touch = event.touches[0]; startY = touch.pageY; startX = touch.pageX; } function touchMove(event) { var touch = event.touches[0]; endY = startY - touch.pageY; endX = startX - touch.pageX; } function touchEnd(event) { //100是給定觸上下方向摸起始的坐標差 if (endY >100||endY<-100) { //jquery中的toggle()方法 $(".div1").toggle(); } //如果不重置,會出現問題 endY = 0; } $("html").attr("id","a") </script> </body> </html>
上面的例子,最好在手機瀏覽器里測試。當手指上下滑動超過給定的值,div的display屬性就會切換。