一:click事件的封裝
手機端的click事件不是太好用,
1.點擊會有延遲,
2.會出現一個灰色區域
就想到了用touch事件代替.
touch事件有touchstart,touchmove,touchend.
在使用的時候會有這樣的一種情況.
現在我想在一個元素上使用touch實現單擊.
意思就是當我的手點下去,在抬起來后觸發事件.
如果我綁定touchstart肯定是不行的:手還沒抬起,就觸發了事件.
如果綁定touchend.會有一些不友好的體驗.
比如:我的手在元素上滑動,然后抬起,就會觸發這個事件.
很明顯有些時候我們只需要類似於單擊事件.這種手滑動后不需要觸發的事件.
下面這個代碼就是一個移動端的click事件.
(function(){ $.fn.touchClick=function(callback){ this.each(function(){ var obj=$(this); obj.on("touchstart",function(){ obj.data("move",false); }).on("touchmove",function(){ obj.data("move",true); }).on("touchend",function(event){ if(obj.data("move")){ return; }else{
if(typeof callback==="function"){
callback(obj,event);
} } obj.data("move",false); }); }); }; })(jQuery);
$("#div").touchClick(function(self,event){ self.hide(); });
二:移動端touch事件的跨頁傳遞.
現在又A,B兩個頁面.上面各有一個元素#a,#b.在當前頁面的同樣位置.
$("#a").on("touchend",function(){ window.location.href="B.html"; });
$("#b").on("touchend",function(){ alert("B"); });
點擊a之后直接跳轉到B.html.但是詭異的是.觸發了b元素的touch事件.
解決辦法.
$("#a").on("touchend",function(){ window.location.href="B.html"; return false });
click事件有三個過程.手按下,手滑動,手抬起.
重新封裝touchclick,使其可以出發這三個事件:
(function(){ var defaults={ start:function(self,event){}, move:function(self,event){}, end:function(self,event){} } $.fn.touchClick1=function(opts){ opts=$.extend({}, defaults,opts); this.each(function(){ var obj=$(this); obj.on("touchstart",function(event){ obj.data("move",false); return opts.start(obj,event); }).on("touchmove",function(event){ obj.data("move",true); return opts.move(obj,event); }).on("touchend",function(event){ if(obj.data("move")){ return; }else{ return opts.end(obj,event); } obj.data("move",false); }); }); }; })(jQuery);
上面的寫法有個弊端,每次想訪問當前對象的都得使用self.不太好。如果直接用this不是更好么。改寫上面的代碼
(function(){ var defaults={ start:function(self,event){}, move:function(self,event){}, end:function(self,event){} } $.fn.touchClick=function(opts){ if(typeof opts=="function"){ opts=$.extend({}, defaults,{end:opts}); }else{ opts=$.extend({}, defaults,opts); } this.each(function(){ var obj=$(this); obj.on("touchstart",function(event){ obj.data("move",false); opts.start.call(this,event); }).on("touchmove",function(event){ obj.data("move",true); opts.move.call(this,event); }).on("touchend",function(event){ if(obj.data("move")){ return; }else{ opts.end.call(this,event); } obj.data("move",false); }); }); }; })(jQuery);