2012-03-26 77 views
2

我有這個水平旋轉木馬組件,我想使它適用於鼠標和滑動事件。 一切工作正常,除了一點:在觸摸設備,我不希望輪播水平滾動,如果用戶試圖垂直滑動滾動瀏覽整個頁面。在觸摸設備中處理滑動

我在做什麼,

  • 在鼠標按下/ touchstart - 我阻止傳播,以避免頁面滾動,項目選擇等第一招事件的事件...
  • ,在旋轉木馬,我設置了一個50ms的超時時間來確定用戶是垂直還是水平移動。
  • 如果DELTAX <移動deltaY,我停止我的水平滾動條,碼的手動觸發touchstart事件,具有標誌指示,我放了一槍碼的手動
  • 我的鼠標按下/ touchstart處理程序中,我讀了「碼的手動」標誌,並且,如果它是真的,我從我的函數返回true,所以所有的默認瀏覽器事件,如頁面垂直滾動,繼續工作。

這是行不通的,我做的所有事情都做出了正確的響應,但是瀏覽器沒有拿起並滾動頁面。我希望我正確解釋自己足以使你們能幫助我...我沒有一個在線的例子,因爲這是我公司的一個「祕密」項目......

感謝

回答

3

我試圖做同樣的事情,你(是?)。關鍵是要檢查touchmove當前的觸摸和最後一次觸摸是否比水平更垂直。如果觸摸更多地從左到右或從右到左,請防止事件的默認設置,否則忽略它。這就是我最終寫的東西。希望它適合你!

var gestures = function() { 
    var self = this, 
    coords = { 
     startX: null, 
     startY: null, 
     endX: null, 
     endY: null 
    }; 

    self.$el.on('touchstart', function(e) { 
     coords.startX = e.originalEvent.targetTouches[0].clientX; 
     coords.startY = e.originalEvent.targetTouches[0].clientY; 
     coords.endX = coords.startX; 
     coords.endY = coords.startY; 
    }); 

    self.$el.on('touchmove', function(e) { 
     var newX = e.originalEvent.targetTouches[0].clientX, 
      newY = e.originalEvent.targetTouches[0].clientY, 
      absX = Math.abs(coords.endX - newX), 
      absY = Math.abs(coords.endY - newY); 

     // If we've moved more Y than X, we're scrolling vertically 
     if (absX < absY) { 
      return; 
     } 

     // Prevents the page from scrolling left/right 
     e.preventDefault(); 

     coords.endX = newX; 
     coords.endY = newY; 
    }); 

    self.$el.on('touchend', function(e) { 
     var swipe = {}, 
      deltaX = coords.startX - coords.endX, 
      deltaY = coords.startY - coords.endY, 
      absX = Math.abs(deltaX), 
      absY = Math.abs(deltaY); 

     swipe.distance = (absX > absY) ? absX : absY; 
     swipe.direction = (absX < absY) ? 
      (deltaY < 0 ? 'down' : 'up') : 
      (deltaX < 0 ? 'right' : 'left'); 

     // console.log(swipe.direction + ' ' + swipe.distance + 'px'); 

     // If we have a swipe of > 50px, let's use it! 
     if (swipe.distance > 50) { 
      if (swipe.direction === 'left') { 
       self.advance(); 
      } else if (swipe.direction === 'right') { 
       self.retreat(); 
      } 
     } 

    }); 
}; 

this是我的滑塊對象和$el是容器元素。