處理Touch事件能讓你了解到用戶的每一根手指的位置,在touch事件觸發的時候產生,可以通過touch event handler的event對象取到,如果基於zepto.js開發,一般是通過event.touches[0]來獲取屬性。重要屬性如下:clientX,clientY:觸摸點相對於瀏覽器窗口viewport的位置;pageX,pageY: 觸摸點相對於頁面的位置;screenX,screenY:觸摸點相對於屏幕的位置 ;identifier:touch對象的unique ID
方法/步驟
-
你可以綁定以下四種Touch事件來了解基本的touch事件:
touchstart:手指觸摸屏幕上的時候觸發
touchmove:手指在屏幕上移動的時候觸發
touchend:手指從屏幕上拿起的時候觸發
touchcancel:系統取消touch事件的時候觸發
-
html:
<div id="touch_test">
<span class="clear">clear</span>
<ul id="touchs">
</ul>
</div>
css:
#touchs{
margin: 10px;width: 100px;height: auto;min-height: 100px;
border:1px solid #c2ddb6;border-radius: 2px;background: #c2ddb6;
}
#touchs li {list-style: none;}
.clear{
margin-left: 10px;display:inline-block;height: 24px;width: 40px;color:#fff;
font-size: 14px;line-height: 24px;background: #c2ddb6;text-align: center;
}
js:
<script type="text/javascript" src="script/zepto.min.js"></script>
<script type="text/javascript">
;(function($){
$('#touchs').find('li').remove();
$('#touchs').bind("touchstart",function(event){
var touchpros =event.touches[0];
console.log(touchpros);
$('#touchs').append('<li>touchstart...</li>');
});
$('#touchs').bind("touchmove",function(){
$('#touchs').append('<li>touchmove...</li>');
});
$('#touchs').bind("touchend",function(){
$('#touchs').append('<li>touchend...</li>');
});
$('#touchs').bind("touchcancel",function(){
$('#touchs').append('<li>touchcancel...</li>');
});
$('.clear').bind("click",function(){
$('#touchs').find('li').remove();
});
})(Zepto);
</script>
-
當你觸摸屏幕並抬起手指,只觸發touchstart和touched。點擊clear 可以清除本次測試的數據,可以再次測試。
-
當如果手指觸摸屏幕並移動后抬起會觸發touchstart,多次touchmove,touchend或touchcanel
-
可以根據基本的touch事件來封裝成你想要實現復雜的效果,比如向左或向右滑動,
向上或向下滑動,並在滑動時封裝你想實現的效果。
打開:https://github.com/madrobby/zepto/tree/master/src;
touch.js封裝好了滑動事件的處理,將其添加到自己的項目中,就可以直接調用向右、右、上、下滑動的事件。這樣zepto.js官網手冊中的例子就可以正常運行了。