2012-02-22 68 views
15

由於touchstart/touchend在大多數桌面瀏覽器中尚未支持。如何創建與mousedown事件相同的touchstart事件(所有瀏覽器均支持該事件)。瀏覽器中的jquery touchstart

我想是這樣的

$('obj').bind('touchstart', function(e){ 
}); 

將被翻譯成

$('obj').bind('mousedown', function(e){ 
}) 

回答

24

您可以一次地結合......

$('obj').bind('touchstart mousedown', function(e){ 
}); 

如果你想mousedown事件自動消防touchstart事件(所以你只需要綁定touchstart)使用...

$(document).bind('mousedown', function(event) { 
    $(event.target).trigger('touchstart'); 
}); 

注意,這意味着自定義touchstart事件可以觸發之前mousedown事件必須傳播到document。這可能會有意想不到的副作用。

+3

這些解決方案可能被證明是有點問題,如果在某些時候這兩個事件將由sa支持我的設備。 – epeleg 2012-06-21 07:54:34

+0

@epeleg當然。在這種情況下,你會在文檔或類似文件中使用''ontouchstart''的代碼,然後相應地選擇你的事件名稱。 – alex 2014-02-14 23:18:43

+0

也許像'if(Modernizr.touchstart){}'會是合適的嗎? – philtune 2015-01-30 14:18:08

7

嘗試是這樣的:

var clickEventType = ((document.ontouchstart!==null)?'click':'touchstart'); 

$('obj').bind(clickEventType, function(e){}); 

更重要的是,使用。對()進行綁定:

$('body').on(clickEventType, 'obj', function(e){}); 

此檢查文件,看是否存在touchstart,如果這樣做,那麼你的活動如果它不是(大多數桌面瀏覽器),那麼它是'touchstart',然後是'click'。

您也可以觸發使用相同的事件類型:

$('obj').trigger(clickEventType); 
+0

我也要求它,所以你可以複製和粘貼整個事情:https://gist.github.com/esteinborn/9398782 – 2014-03-06 20:32:00

1

這不是最好的解決辦法,但我發現到現在最好的。倒臺?它只能在首先觸摸發生,所以你不能同步使用:(

var isTouch = false; 
$('body').on('touchstart', function() { 
    isTouch = true; 
}); 

您也可以檢查,如果瀏覽器支持觸摸先用Modernizr的例如。

記得做在全球範圍內不使用它(除非你必須),你也可以通過在isTouch = true代碼後添加is-touch-device class到Html標籤來將其更改爲「modernizr」類似的代碼:$('html').addClass('is-touch-device')。在這種情況下,你可以從任何地方引用它(也可以從css)