有這樣的需求需要在手機端預覽圖片的時候,實現圖片的手勢拖動,放大縮小功能。最終通過touch.js這個插件實現了效果。或者PinchZoom.js是一個Javript庫,提供多點觸摸手勢縮放和拖動任何DOM元素;這里我介紹的就是touch.js
Touch.js是移動設備上的手勢識別與事件庫, 由百度雲Clouda團隊維護,也是在百度內部廣泛使用的開發工具.
Touch.js的代碼已托管於github並開源,希望能幫助國內更多的開發者學習和開發出優秀的App產品.
Touch.js手勢庫專為移動設備設計, 請在Webkit內核瀏覽器中使用.
var target = document.getElementById("imgView");
target.style.webkitTransition = 'all ease 0.05s';
touch.on('#imgView', 'touchstart', function (ev) {
ev.preventDefault();
});
var initialScale = -10;
var currentScale;
var dx, dy;
touch.on('#imgView', 'pinchend', function (ev) {
if ($("#imgView").hasClass('viewerimg')) {
$("#imgView").removeClass("viewerimg");
};
currentScale = ev.scale - 1;
currentScale = initialScale + currentScale;
currentScale = currentScale > 2 ? 2 : currentScale;
currentScale = currentScale < 1 ? 1 : currentScale;
if (currentScale == 1) {
$("#imgView").addClass("viewerimg");
};
this.style.webkitTransform = 'scale(' + currentScale + ')';
console.log("當前縮放比例為:" + currentScale + ".");
});
touch.on('#imgView', 'pinchend', function (ev) {
initialScale = currentScale;
});
touch.on('#imgView', 'drag', function (ev) {
dx = dx || 0;
dy = dy || 0;
this.style.webkitTransform = 'scale(' + currentScale + ')';
console.log("當前x值為:" + dx + ", 當前y值為:" + dy + ".");
var offx = dx + ev.x + "px";
var offy = dy + ev.y + "px";
this.style.webkitTransform = "translate3d(" + offx + "," + offy + ",0)";
});
touch.on('#imgView', 'dragend', function (ev) {
dx += ev.x;
dy += ev.y;
});
html代碼
<style>
.viewerimg {
width: 100%;
height: auto;
}
</style>
<img id="imgView" class="viewerimg" draggable="true"src="{{img.url}}" alt="{{img.name}}" title="{{img.name}}">
