1 回答

TA貢獻1797條經驗 獲得超6個贊
/*
* @Author 兔爺
* @function 實現單指拖動圖片,雙指縮放圖片
* @marks 參數one是為了區分屏幕上現在是一根手指還是兩根手指,因為在滑動的時候兩根手指先離開一根會觸發一根手指移動圖片位置這個方法
*/
var touchScale = function(seletor, bg) {
var startX, endX, scale, x1, x2, y1, y2, imgLeft, imgTop, imgWidth, imgHeight,
one = false,
$touch = $(seletor),
originalWidth = $touch.width(),
originalHeight = $touch.height(),
baseScale = parseFloat(originalWidth/originalHeight),
imgData = [],
bgTop = parseInt($(bg).css('top'));
function siteData(name) {
imgLeft = parseInt(name.css('left'));
imgTop = parseInt(name.css('top'));
imgWidth = name.width();
imgHeight = name.height();
}
$(document).on('touchstart touchmove touchend', $(seletor).parent().selector, function(event){
var $me = $(seletor),
touch1 = event.originalEvent.targetTouches[0], // 第一根手指touch事件
touch2 = event.originalEvent.targetTouches[1], // 第二根手指touch事件
fingers = event.originalEvent.touches.length; // 屏幕上手指數量
//手指放到屏幕上的時候,還沒有進行其他操作
if (event.type == 'touchstart') {
if (fingers == 2) {
// 縮放圖片的時候X坐標起始值
startX = Math.abs(touch1.pageX - touch2.pageX);
one = false;
}
else if (fingers == 1) {
x1 = touch1.pageX;
y1 = touch1.pageY;
one = true;
}
siteData($me);
}
//手指在屏幕上滑動
else if (event.type == 'touchmove') {
if (fingers == 2) {
// 縮放圖片的時候X坐標滑動變化值
endX = Math.abs(touch1.pageX - touch2.pageX);
scale = endX - startX;
$me.css({
'width' : originalWidth + scale,
'height' : (originalWidth + scale)/baseScale,
'left' : imgLeft,
'top' : imgTop
});
}else if (fingers == 1) {
x2 = touch1.pageX;
y2 = touch1.pageY;
if (one) {
$me.css({
'left' : imgLeft + (x2 - x1),
'top' : imgTop + (y2 - y1)
});
}
}
}
//手指移開屏幕
else if (event.type == 'touchend') {
// 手指移開后保存圖片的寬
originalWidth = $touch.width(),
siteData($me);
imgData = [[imgLeft, imgTop-bgTop, imgWidth, imgHeight],[0, 0, 640, 640]];
}
});
var getData = function(){
return imgData;
};
return {
imgData : getData
}
};
這是我之前寫的單指拖動,雙指縮放的js代碼,希望對你有所幫助,用前請調用jquery。
添加回答
舉報