[jsjquery]移动端⼿势拖动,放⼤,缩⼩预览图⽚
摘要
有这样的需求需要在⼿机端预览图⽚的时候,实现图⽚的⼿势拖动,放⼤缩⼩功能。最终通过touch.js这个插件实现了效果。touch.js
Touch.js是移动设备上的⼿势识别与事件库, 由百度云Clouda团队维护,也是在百度内部⼴泛使⽤的开发⼯具.
Touch.js的代码已托管于github并开源,希望能帮助国内更多的开发者学习和开发出优秀的App产品.
Touch.js⼿势库专为移动设备设计, 请在Webkit内核浏览器中使⽤.
核⼼代码
imgView为图⽚的容器img标签。
var target = ElementById("imgView");
target.style.webkitTransition = 'all ease 0.05s';
<('#imgView', 'touchstart', function (ev) {
ev.preventDefault();
});
var initialScale = -10;
var currentScale;
var dx, dy;
<('#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 + ".");
});
<('#imgView', 'pinchend', function (ev) {
initialScale = currentScale;
});
<('#imgView', 'drag', function (ev) {
jquery在线图片
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)";
});
<('#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}}">
刚开始加载的时候,让图⽚宽度跟随屏幕的宽度⾃适应。这⾥实现的是⼿势放⼤2,缩⼩时变为1,只有两种⼤⼩。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。