Javascript 高级手势使用介绍

2020-04-21 07:20:19易采站长站整理

点击

最基本的手势识别是点击。当检测到点击时,将会在手势对象的目标元素触发

MSGestureTap
事件。不同于单击事件,点击手势只能在用户触摸、按鼠标按钮或使用手写笔触控而不移动时触发。如果您要区分用户点击元素和拖动元素的操作,这一点通常会显得十分有用。

长按

长按手势是指用户使用一个手指触摸屏幕,并保持片刻并抬起而不移动的操作。在长按交互期间,

MSGestureHold
事件会针对手势的各种状态而多次触发:

复制代码
element.addEventListener(“MSGestureHold”, handleHold);
function handleHold(evt) {
if (evt.detail & evt.MSGESTURE_FLAG_BEGIN) {
// Begin signals the start of a gesture. For the Hold gesture, this means the user has been holding long enough in place that the gesture will become a complete press & hold if the finger is lifted.
}
if (evt.detail & evt.MSGESTURE_FLAG_END) {
// End signals the end of the gesture.
}
if (evt.detail & evt.MSGESTURE_FLAG_CANCEL) {
// Cancel signals the user started the gesture but cancelled it. For hold, this occurs when the user drags away before lifting. This flag is sent together with the End flag, signaling the gesture recognition is complete.
}
}

动态手势(收缩、旋转、轻扫和拖动)

动态手势(例如,收缩或旋转)将以转换的形式报告,这与 CSS 2D 转换颇为类似。动态手势可触发三种事件:

MSGestureStart
MSGestureChange
(随着手势的持续而重复触发)和
MSGestureEnd
。每个事件都包含缩放(收缩)、旋转、转换和速度等相关信息。

由于动态手势以转换的形式报告,因此使用包含 CSS 2D 转换的

MSGesture
来操作诸如照片或拼图等元素将变得十分轻松。例如,您可以通过下列方式启用缩放、旋转和拖动元素的操作:

复制代码
targetElement.addEventListener(“MSGestureChange”, manipulateElement);
function manipulateElement(e) {
// Uncomment the following code if you want to disable the built-in inertia provided by dynamic gesture recognition
// if (e.detail == e.MSGESTURE_FLAG_INERTIA)
// return;
var m = new MSCSSMatrix(e.target.style.transform); // Get the latest CSS transform on the element
e.target.style.transform = m
.translate(e.offsetX, e.offsetY) // Move the transform origin under the center of the gesture
.rotate(e.rotation * 180 / Math.PI) // Apply Rotation
.scale(e.scale) // Apply Scale
.translate(e.translationX, e.translationY) // Apply Translation
.translate(-e.offsetX, -e.offsetY); // Move the transform origin back