前面写过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属性就会切换。