2012-05-18 124 views
0

我想弄清楚如果用戶代理是觸摸設備,如果是我要加載的addEventListener ...EventListener的觸摸設備的

if((navigator.userAgent.match(/iPhone/i)) || 
    (navigator.userAgent.match(/iPad/i)) { 
    document.addEventListener("touchstart", function() {},false); 
}) 

此外,我怎麼能檢測的Android設備和可能的其他觸摸設備?

+1

這裏的答案.. if(window.Touch){/ * JavaScript爲您的觸摸界面* /} – Josh

+1

瀏覽器嗅探是不好的,從來沒有使用它,總是有其他選擇。有許多觸摸設備不是iPhone或iPad,而Android可以在各種可能或不可以支持觸摸事件的設備上運行。然後是Windows Mobile(或最近稱爲的任何東西)。 – RobG

+0

不要忘記'MSPointer'事件。 – Sampson

回答

0

我用前一段時間來測試觸摸事件一個簡單的腳本是:

var hasTouch = (function(){ 
    if (document && document.createEvent) { 
    try { 
     document.createEvent('GestureEvent'); 
     document.createEvent('TouchEvent'); 
     return true; 
    } catch (e) { 
     return false; 
    } 
    } 
})(); 

我沒有用了一段時間,所以有可能是更好的方法,但上面仍然有效。

您也可以嘗試Kangax的文章Detecting event support without browser sniffing,這可能會去是這樣的:

function isTouchEventSupported(eventName) { 
    var el = document.createElement('div'); 
    eventName = 'on' + eventName; 
    var isSupported = (eventName in el); 

    if (!isSupported) { 
     el.setAttribute(eventName, 'return;'); 
     isSupported = typeof el[eventName] == 'function'; 
    } 
    el = null; 
    return isSupported; 
    } 

    alert(isTouchEventSupported('touchstart')); // false in IE 8