2011-06-23 48 views
19

我正在處理一些觸摸事件和手勢,我希望能夠縮放和旋轉對象,我已經成功地將它拖動,但手勢給了我麻煩。這些手勢正在工作,但它們不穩定,無論何時捏住它以放大或縮小或嘗試旋轉它,它都會從手指跳到手指。Javascript zoom and rotate使用gesturechange和gestureend

這裏是我的代碼供參考。

var width = 300; var height = 300; var rotation = 0; 
$('.dynamic').live("gesturechange gestureend", function(e){ 
var orig = e.originalEvent; 

if(e.type == 'gesturechange'){ 
    e.preventDefault(); 
    $(this).css("width", parseFloat(width) * orig.scale); 
    $(this).css("height", parseFloat(height) * orig.scale); 
    $(this).css("-webkit-transform","rotate(" + ((parseFloat(rotation) + orig.rotation) % 360) + "deg)"); 
}else if(e.type == 'gestureend'){ 
    a.w[ids] = parseFloat(width) * orig.scale; 
    a.h[ids] = parseFloat(height) * orig.scale; 
    a.rotation[ids] = (parseFloat(rotation) + orig.rotation) % 360; 
} 
}); 

有沒有辦法使這個順利,並防止它從手指跳,或者是我錯誤的方法。在需要一些技巧和竅門和幫助

找到了解決辦法

似乎是拖了我的觸摸事件與手勢干擾這就是爲什麼它一直從手指跳躍的手指,解決這個問題的方法是不使用手勢反而會計算對象的觸摸,並使用觸摸開始,結束和更改。

下面是代碼

var touches = 0; var width = 300; var height = 300; var rotation = 0; 
$('.dynamic').live("touchstart touchmove touchend", function(e){ 
var orig = e.originalEvent; 

if(e.type == 'touchstart'){ 
if(orig.touches.length == 1){ 
    touches = 1; 
}else if(orig.touches.length == 2){ 
    touches = 2; 
} 
}else if(e.type == 'touchmove'){ 
e.preventDefault(); 
if(touches == 2){ 
     $(this).css("width", parseFloat(width) * orig.scale); 
     $(this).css("height", parseFloat(height) * orig.scale); 
     $(this).css("-webkit-transform","rotate(" + ((parseFloat(rotation) + orig.rotation) % 360) + "deg)"); 
} 
}else if(e.type == 'touchend'){ 
    if(touches == 2){ 
     a.w[ids] = parseFloat(width) * orig.scale; 
     a.h[ids] = parseFloat(height) * orig.scale; 
     a.rotation[ids] = (parseFloat(rotation) + orig.rotation) % 360; 
    } 
} 
}); 
+3

非常感謝您發佈您的答案!通常的做法是將其作爲答案發布,而不是將其編輯到問題中。 (回答你自己的問題沒有錯。) – RichieHindle

+0

它不讓我回答它,因爲我在這裏是新的 – ryuutatsuo

+0

你的第一個方法在Android 2.x上工作嗎?我想支持捏手勢,但第二種方法(細粒度觸摸支持)僅適用於iOS(以及Android 3.0 /平板電腦和WebOS?)。感謝您發佈您的解決方案! –

回答

10

你的解決方案的工作,但它不是最優雅:你仍然可以使用你的第一段代碼,並依靠gesture事件。
您只需確保touch事件處理程序不會干擾您的gesture
只需添加這到touch事件處理程序:

$('.dynamic').live("touchstart touchmove touchend", function(e){ 
    if(e.originalEvent.touches.length > 1) 
     return; 
    /* your touch code here */ 
}); 

,然後使用現有的動作代碼:

$('.dynamic').live("gesturechange gestureend", function(e){ 
    /* your gesture code here */ 
}); 

這應該工作,因爲手勢事件被觸發只有有兩個或兩個以上手指觸摸屏幕,並且在發生這種情況時不會執行其他代碼,因爲觸摸事件處理程序僅響應一次觸摸。

0

也許jquery不是這項任務的最佳選擇。你可以考慮使用sencha touch。它已經做了你想要的很好。看看demos。取決於你想要做什麼jQuery Mobile也是一個不錯的選擇。