触控浏览:使用手势事件超越平移、缩放和点击





0/5 (0投票)
触控浏览:使用手势事件超越平移、缩放和点击
像 Internet Explorer 10 这样的新浏览器,使用手势事件提供了先进的触控体验。 您可以采取一些 初步措施 来确保您的网站对触控友好,同时也能在支持许多现代浏览器的前提下,在多种输入设备上良好运行。在本文中,我将向您展示如何实现这一点。
让我们从一个手势事件开始,即 Browser Surface 测试驱动演示。
这引入了 JavaScript 中的 手势识别对象。 网站可以创建手势对象,决定要处理哪些指针(鼠标、笔或触摸点),并将手势事件定向到所需的任何元素。 然后浏览器会计算正在执行的手势,并通过事件通知页面。 这使开发人员能够构建其他任何浏览器尚未原生支持的手势体验。 这些包括多个并发手势,例如,用您的双手旋转两个拼图。
让我们看看这在代码中是如何工作的。
创建手势对象
在您的网站中处理手势的第一步是实例化一个手势对象。
var myGesture = new MSGesture();
接下来,给手势一个目标元素。 这是浏览器将触发手势事件的元素。 它也是确定事件坐标空间的元素。
elm = document.getElementById("someElement"); myGesture.target = elm; elm.addEventListener("MSGestureChange", handleGesture);
最后,告诉手势对象在手势识别中要处理哪些指针。
elm.addEventListener("MSPointerDown", function (evt) { // adds the current mouse, pen, or touch contact for gesture recognition myGesture.addPointer(evt.pointerId); });
注意:不要忘记您需要使用 –ms-touch-action 来 配置元素以不执行默认的触摸 操作,例如平移和缩放,而是为输入提供指针事件。
处理手势事件
一旦手势对象具有有效的目标并且至少有一个指针添加到它,它将开始触发手势事件。 手势事件有两种类型:静态手势(如点击或按住)和动态手势(如捏合、旋转或滑动)。
点按
最基本的手势识别是点击。 当检测到点击时,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
。 每个事件都包含关于缩放(捏合)、旋转、平移和速度的 信息。
由于动态手势报告变换,因此很容易将 MSGesture
与 CSS 2D 变换结合使用来操作元素,例如照片或拼图。 例如,您可以启用元素的缩放、旋转和拖动,如下所示
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; // Get the latest CSS transform on the element var m = new MSCSSMatrix(e.target.style.transform); 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 }
通过分别按住 CTRL 或 SHIFT 修饰键旋转鼠标滚轮,鼠标支持缩放和旋转等动态手势。
您可以通过 MSGesture 对象 和 MSGesture 事件 的深入文档了解更多信息。