2013-01-18 50 views
11

因此,我在處理Microsoft Surface的Web應用程序時遇到了一個有趣的問題。在使用觸摸和鼠標的設備(例如Surface)上監聽mousedown和touchstart

我想爲用戶與DOM元素進行交互時添加事件偵聽器。現在,我可以這樣做:

if ('ontouchstart' in document.documentElement) { 
    //Attach code for touch event listeners 
    document.addEventListener("touchstart" myFunc, false); 
} else { 
    //Attach code for mouse event listeners 
    document.addEventListener("mousedown" myFunc, false); 
} 

如果設備沒有鼠標輸入,這個問題將是簡單和上面的代碼會工作得很好。但Surface(和許多新的Windows 8計算機)都具有觸摸和鼠標輸入。所以上面的代碼只有在用戶觸摸設備時纔會起作用。鼠標事件偵聽器將永遠不會被附加。

於是我想,好吧,我可以這樣做:

if ('ontouchstart' in document.documentElement) { 
    //Attach code for touch event listeners 
    document.addEventListener("touchstart" myFunc, false); 
} 
//Always attach code for mouse event listeners 
document.addEventListener("mousedown" myFunc, false); 

設備不支持觸摸不會有附加的事件,但使用觸摸將註冊其處理的設備。這個雖然問題是myFunc()將在觸摸屏設備上被調用兩次:當「touchstart」引發

  • 由於觸摸瀏覽器通常要經過週期touchstart

    1. myFunc()將火 - >touchmove - >touchend - >鼠標按下 - >鼠標移動 - >鼠標鬆開 - >點擊myFunc()將再次在「鼠標按下」

    叫我考慮過將代碼添加到myFunc(),使得它調用e.preventDefault()但這似乎也阻擋touchend以及鼠標按下/鼠標移動/鼠標鬆開某些瀏覽器上的link)。

    我討厭做useragent嗅探器,但它好像觸摸瀏覽器在觸摸事件的實現方式上有所不同。

    我必須錯過一些東西,因爲它似乎肯定這些JavaScript實現是由瀏覽器支持鼠標和觸摸的可能性決定的!

  • +0

    考慮到Surface不能運行Android,這與Android有什麼關係? – CommonsWare

    +0

    @CommonsWare - 我的問題與支持鼠標的所有觸控設備有關,因此它似乎適用於Windows 8和Android。 – userx

    +0

    是的,chromeOS呢? –

    回答

    -3

    編輯: 如果使用jQuery,你就可以這樣做:

    var clickEventType=((document.ontouchstart!==null)?'mousedown':'touchstart'); 
    
    $("a").bind(clickEventType, function() { 
        //Do something 
    }); 
    

    這將觸發只有綁定的事件之一。

    這裏找到:How to bind 'touchstart' and 'click' events but not respond to both?

    +1

    這並不能解決問題。它只是爲這兩個事件附加處理程序,因此我不相信它會阻止事件觸發的可能性(因此也會阻止附加功能觸發兩次)。 – userx

    +0

    你是對的 –

    0

    裏面myFunc的,檢查事件類型。如果是touchstart,那麼做e.stopPropagation()

    function myFunc(e) { 
        if (e.type === 'touchstart') { 
         e.stopPropagation(); 
        } 
        //the rest of your code here 
    } 
    
    +0

    這個不幸的是不起作用,因爲它可能是一個Windows 8筆記本電腦上的鼠標和觸摸屏「mousedown」事件。 – userx

    +0

    編輯我的答案。 – noypiscripter

    2

    對於Windows 8,您可以使用「MSPointerDown」事件。

    if (window.navigator.msPointerEnabled) { 
        document.addEventListener("MSPointerDown" myFunc, false); 
    } 
    

    也將添加以下到你的風格:

    html { 
        -ms-touch-action: none; /* Direct all pointer events to JavaScript code. */ 
        } 
    

    更多信息,請參見http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx

    +0

    可能會禁用滾動 –