2011-11-24 74 views
7

使用什麼比jQuery lib更多;我正在嘗試在拖動它的右邊框時調整DIV的大小。它可以與鼠標完美配合,但無法在觸控設備上使用。我認爲這與e.touches有關。使用觸摸調整HTML元素的大小

我試過用e.touchese.targetTouches;他們似乎都沒有工作。

我在執行touch events部分權利?我錯過了什麼?

這是一個fiddle,以及下面的完整代碼。

HTML:

<div class="container"><div class="handle"></div></div> 

CSS:

.container{background:#CCC;width:200px;height:100px;position:relative;overflow:hidden;} 
.handle{cursor:e-resize;height:100px;width:2px;position:absolute;top:0;right:0;background:red;} 

JS:

var handle = null; 

$(".handle").on('mousedown touchstart', function(e){ 
    handle = { 
     x : e.pageX, 
     p : $(this).parent(), 
     pw: $(this).parent().width() 
    }; 

    if (e.targetTouches){ //e.touches 
     handle.x = e.targetTouches[0].pageX //e.touches[0] 
    } 

    e.preventDefault(); 
}); 

$(document).on({ 
    'mousemove touchmove':function(e){ 
     if(handle) { 
      if (e.targetTouches){ //e.touches 
       handle.p.width(handle.pw+(e.targetTouches[0].pageX - handle.x)); //e.touches[0]    
      }else{ 
       handle.p.width(handle.pw+(e.pageX - handle.x));      
      } 
     } 
     e.preventDefault(); 
    }, 
    'mouseup touchend':function(e){ 
     handle = null; 
     e.preventDefault(); 
    } 
}); 

任何幫助,將不勝感激!

+0

你有沒有打開你的JavaScript控制檯或檢查員,看看是否有任何錯誤彈出?只是要知道事件是否真的在觸摸屏設備上正常觸發。 – marcio

+0

@marcioAlmada謝謝,實際上console.log()在附加if(e.touches)或if(e.targetTouches) – Pierre

回答

3

而不是e.targetTouches你應該使用e.originalEvent.touches

Allso這將有助於有:

  • gesturechange事件一起mousemove touchmove
  • gestureend事件一起mouseup touchend
  • gesturestart事件一起mousedown touchstart

另一個改進是在文件mousemove事件回調移動e.preventDefault()在if語句中,如果句柄爲null,用戶可以滾動頁面。

+2

謝謝!它的工作,這正是我想念的!由於我使用jQuery進行綁定,因此我需要到達OriginalEvent! – Pierre

1

我在做web應用程序時遇到了同樣的問題,並發現這個問題解決了我的問題jquery touch plugin

下載這個插件,幷包括在你的HTML文件,你完成了。你不需要調用任何touchstart/touchmove事件。

如果不工作,你可以添加觸摸事件是這樣的:

$('Element').addTouch(); 

呼叫addTouch()方法爲每一個元素,你whant到觸摸事件做出響應。

檢查this鏈接的更多下載選項。

+1

歡呼聲時根本沒有觸發,但我試圖避免任何「插件」。 – Pierre